前言

一提到python爬虫,词云图,就头大,我们就从简单开始,一步一步进行

python爬虫

一、基本框架

此代码只对python的基本框架进行描述

# -*- coding: utf-8 -*-#
#基本框架#一、库的引用
from bs4 import BeautifulSoup  # 网页解析,获取数据
import re  # 正则表达式,进行文字匹配
import urllib.request, urllib.error  # 制定URL,获取网页数据
#二、主函数
def main():a = 1# 爬取网页,获取数据baseurl = "https://news.163.com/"Datelist = getDate(baseurl)#保存savepath = ".\\新闻2.xls"saveDate(savepath, Datelist, a)# 三、爬网页
def getDate(baseurl, a):datelist = []          #存为列表
#四、保存
def saveDate(savepath, Datelist, a):print("...")if __name__ == "__main__":main()

二、爬取网页

爬取网页首先我们需要获取网页链接,我们定义一个函数名字叫做:askURL(url)

爬取了网页接下来我们需要的就是获取网页内容,我们写一个叫做 getData(baseUrl)的函数

from bs4 import BeautifulSoup  # 网页解析,获取数据
import urllib.request, urllib.error  # 制定URL,获取网页数据def main():a = 1# 爬取网页,获取数据baseurl = "https://news.163.com/"Datelist, a = getDate(baseurl, a)savepath = ".\\新闻2.xls"saveDate(savepath, Datelist, a)# 得到指定URL的网页内容
def askURL(url):head = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763"}# 模拟浏览器头部信息,向服务器发送消息request = urllib.request.Request(url, headers=head)html = ""   #字符串存try:response = urllib.request.urlopen(request)html = response.read().decode("utf-8", 'ignore')print(html)except urllib.error.URLError as e:if hasattr(e, "code"):print(e.code)if hasattr(e, "reason"):print(e.reason)return html
#爬网页
def getDate(baseurl, a):datelist = []          #存为列表html = askURL(baseurl)soup = BeautifulSoup(html, "html.parser")return datelist, a#保存
def saveDate(savepath, Datelist, a):print("...")if __name__ == "__main__":main()

实现了如图所示的代码,但是数据很杂乱且庞大,我们还需做到数据的清洗

三、数据清洗

# -*- coding: utf-8 -*-#
from bs4 import BeautifulSoup  # 网页解析,获取数据
import re  # 正则表达式,进行文字匹配
import urllib.request, urllib.error  # 制定URL,获取网页数据def main():a = 1# 爬取网页,获取数据baseurl = "https://news.163.com/"Datelist, a = getDate(baseurl, a)savepath = ".\\新闻2.xls"saveDate(savepath, Datelist, a)# 得到指定URL的网页内容
def askURL(url):head = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763"}# 模拟浏览器头部信息,向服务器发送消息request = urllib.request.Request(url, headers=head)html = ""   #字符串存try:response = urllib.request.urlopen(request)html = response.read().decode("utf-8", 'ignore')# print(html)except urllib.error.URLError as e:if hasattr(e, "code"):print(e.code)if hasattr(e, "reason"):print(e.reason)return html
#爬网页
def getDate(baseurl, a):datelist = []          #存为列表html = askURL(baseurl)soup = BeautifulSoup(html, "html.parser")for item in soup.select(".hidden"):  # 查找符合要求的字符串,形成列表for c in item.select('a'):print(c)return datelist, a#保存
def saveDate(savepath, Datelist, a):print("...")if __name__ == "__main__":main()

四、保存数据

爬取到了数据接下来我们需要保存数据(这里我们采取保存数据到excel中)

# -*- coding: utf-8 -*-#
from bs4 import BeautifulSoup  # 网页解析,获取数据
import re  # 正则表达式,进行文字匹配
import urllib.request, urllib.error  # 制定URL,获取网页数据
import xlwt  # 进行excel操作def main():a = 1# 爬取网页,获取数据baseurl = "https://news.163.com/"Datelist, a = getDate(baseurl, a)savepath = "新闻2.xls"saveDate(savepath, Datelist, a)# 得到指定URL的网页内容
def askURL(url):head = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763"}# 模拟浏览器头部信息,向服务器发送消息request = urllib.request.Request(url, headers=head)html = ""   #字符串存try:response = urllib.request.urlopen(request)html = response.read().decode("utf-8", 'ignore')# print(html)except urllib.error.URLError as e:if hasattr(e, "code"):print(e.code)if hasattr(e, "reason"):print(e.reason)return htmlfindlink = re.compile(r'<a href="(.*?)">')
findjs = re.compile(r'">(.*)</a>')#爬网页
def getDate(baseurl, a):datelist = []          #存为列表html = askURL(baseurl)soup = BeautifulSoup(html, "html.parser")for item in soup.select(".hidden"):  # 查找符合要求的字符串,形成列表for c in item.select('a'):#print(c)date = []c = str(c)Js = findjs.findall(c)date.append(Js)Link = findlink.findall(c)date.append(Link[0])date.append('')Html = askURL(Link[0])Soup = BeautifulSoup(Html, "html.parser")for item1 in Soup.select(".post_body"):date.insert(2, item1.get_text().strip())print("已保存第%.3d条新闻数据" % a)a += 1datelist.append(date)return datelist, a#保存
def saveDate(savepath, Datelist, a):book = xlwt.Workbook(encoding="utf-8", style_compression=0)  # 创建workbook对象sheet = book.add_sheet(savepath, cell_overwrite_ok=True)  # 创建工作表crl = ("新闻标题", "新闻链接", "新闻内容")for i in range(0, len(crl)):sheet.write(0, i, crl[i])for i in range(1, a):for j in range(0, len(crl)):sheet.write(i, j, Datelist[i - 1][j])print("保存完毕")book.save(savepath)if __name__ == "__main__":main()

词云图

使用时需要引用wordcloud  和 matplotlib,具体的效果图如下

from wordcloud import WordCloud
import matplotlib.pyplot as plt#打开文本
text=open('头条新闻.txt',encoding="utf-8").read()#生成
#字体地址,图片长宽,背景颜色
wc=WordCloud(font_path='C:\Windows\Fonts\msyh.ttc',width=800,height=600,mode="RGBA",background_color='white').generate(text)#显示
plt.imshow(wc)
plt.axis("off")#消除坐标
plt.show()#保存
wc.to_file("2.wordcloud2.png")

再进一步

虽然已经制作出了词云图,但长长的句子并不是我们的本意,我们得引入分词模块

from wordcloud import WordCloud
import matplotlib.pyplot as plt
import jieba#打开文本
text=open('头条新闻.txt',encoding="utf-8").read()
#中文分词
text=' '.join(jieba.cut(text))#形成列表,将列表里的词用空格分开并拼成长字符串
#生成
#字体地址,图片长宽,背景颜色
wc=WordCloud(font_path='C:\Windows\Fonts\msyh.ttc',width=800,height=600,mode="RGBA",background_color='white').generate(text)
#显示
plt.imshow(wc)
plt.axis("off")#消除坐标
plt.show()
#保存
wc.to_file("2.wordcloud2.png")

写在最后

python爬取新闻,制作词云图相关推荐

  1. python处理数据集并制作词云图

    python处理数据集并制作词云图 处理数据 使用自定义词典 去掉停用词 词频统计 绘制词云图+美化 1.处理数据 这里是老师给的新闻数据集,里面有5个类别的新闻数据,我以cars这一类为例. 将cs ...

  2. python爬取新闻并归数据库_Python爬取数据并写入MySQL数据库操作示例

    Python爬取数据并写入MySQL数据库的实例 首先我们来爬取 http://html-color-codes.info/color-names/ 的一些数据. 按 F12 或 ctrl+u 审查元 ...

  3. python爬取新闻存入数据库_python 爬取古诗文存入mysql数据库的方法

    使用正则提取数据,请求库requests,看代码,在存入数据库时,报错ERROR 1054 (42S22): Unknown column 'title' in 'field list'.原来是我写s ...

  4. python爬取新闻存入数据库_Python爬取数据并写入MySQL数据库的实例

    按 F12 或 ctrl+u 审查元素,结果如下: 结构很清晰简单,我们就是要爬 tr 标签里面的 style 和 tr 下几个并列的 td 标签,下面是爬取的代码: #!/usr/bin/env p ...

  5. python爬取新闻存入数据库_python爬取数据存入数据库

    昨天本来写了一篇关于python爬取的文章,结果没通过,正好今天一起吧.用python同时实现爬取,和存入数据库,算是复习一下前面操作数据库的知识. 1.准备工作 既然是爬取,那自然要连接到爬取的页面 ...

  6. Python爬取新闻标题及链接存至 Excel(含源码)

    新闻网址: https://www.tsinghua.edu.cn/news.htm 本片文章实现爬取新闻标题和链接 将新闻标题及链接存储至 Excel 表 源码 # 清华新闻import panda ...

  7. python爬取歌词生成词云图_爬取毛不易歌词作词云展示

    爬取毛不易歌词作词云展示 今天我们做一个数据可视化的项目,爬取毛不易的歌词做词云展示. 1.爬取数据 我们主要使用 Python 爬虫获取 HTML,用 XPath 对歌曲的 ID.名称进行解析,然后 ...

  8. python爬取新闻后提炼_Python爬虫开发的3大难题,别上了贼船才发现,水有多深...

    写爬虫,是一个非常考验综合实力的活儿.有时候,你轻而易举地就抓取到了想要的数据:有时候,你费尽心思却毫无所获. 好多Python爬虫的入门教程都是一行代码就把你骗上了"贼船",等上 ...

  9. python爬取新闻发送微信_如何利用 Python 爬虫实现给微信群发新闻早报?(详细)...

    image 1. 场景 经常有小伙伴在交流群问我,每天的早报新闻是怎么获取的? image 其实,早期使用的方案,是利用爬虫获取到一些新闻网站的标题,然后做了一些简单的数据清洗,最后利用 itchat ...

最新文章

  1. Beta阶段总结博客(麻瓜制造者)
  2. 一些前端面试题(一)
  3. 【逆向知识】裸函数(Naked函数)
  4. arrayQueue
  5. FPGA积沙成塔(目录篇)
  6. 紫金计算机网络,江苏省计算机网络技术重点实验室
  7. django日志使用TimeRotateFileHandler
  8. table中的td表示table data(表格数据),tr表示table row(表格行),th表示table head(表格头)
  9. 如何使用cURL一次测量请求和响应时间?
  10. catv系统主要有哪三部分组成_光纤通信系统的组成与特点
  11. cc2640蓝牙数据接收丢包问题
  12. vb6计算机,[计算机软件及应用]VB6.ppt
  13. RF 操作页面滚动条上下滚动
  14. css版权备案等居于页面底部与超出不换行可滑动
  15. NUC系列迷你电脑改装苹果网卡的又一神器方案
  16. dnf史诗计算机手机版,DNF手游终于要来了!可端游的史诗级装备该咋办…
  17. 三国志战略版:Daniel_袁术分析
  18. 【Aegisub相关】math.random 行为记录
  19. 1万条xml文件的写入,附加杂类知识
  20. Java web项目创建笔记23 之《spring整合xxl-job》

热门文章

  1. python利用server酱推送IP地址
  2. JavaScript游戏开发(3)(笔记)
  3. Python高级编程-如何将多个小字符串拼接成一个大的字符串?
  4. 通过金矿模型介绍动态规划(经典入门)
  5. 基于深度学习的文本摘要自动生成(自然语言处理)-本科毕业设计(附完整代码及数据集)
  6. HTML5布局—div布局和table布局
  7. 入门后指针进阶习题深度分析
  8. 这4款免费的超实用网站,我真的忍不住分享,太棒了!
  9. 如何把WORD文档的页眉页脚中的那一条横线去掉
  10. 对象的创建、发布、逸出