• python爬取新闻,制作词云图


    前言

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

    python爬虫

    一、基本框架

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

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

    二、爬取网页

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

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

    1. from bs4 import BeautifulSoup # 网页解析,获取数据
    2. import urllib.request, urllib.error # 制定URL,获取网页数据
    3. def main():
    4. a = 1
    5. # 爬取网页,获取数据
    6. baseurl = "https://news.163.com/"
    7. Datelist, a = getDate(baseurl, a)
    8. savepath = ".\\新闻2.xls"
    9. saveDate(savepath, Datelist, a)
    10. # 得到指定URL的网页内容
    11. def askURL(url):
    12. head = {
    13. "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"}
    14. # 模拟浏览器头部信息,向服务器发送消息
    15. request = urllib.request.Request(url, headers=head)
    16. html = "" #字符串存
    17. try:
    18. response = urllib.request.urlopen(request)
    19. html = response.read().decode("utf-8", 'ignore')
    20. print(html)
    21. except urllib.error.URLError as e:
    22. if hasattr(e, "code"):
    23. print(e.code)
    24. if hasattr(e, "reason"):
    25. print(e.reason)
    26. return html
    27. #爬网页
    28. def getDate(baseurl, a):
    29. datelist = [] #存为列表
    30. html = askURL(baseurl)
    31. soup = BeautifulSoup(html, "html.parser")
    32. return datelist, a
    33. #保存
    34. def saveDate(savepath, Datelist, a):
    35. print("...")
    36. if __name__ == "__main__":
    37. main()

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

    三、数据清洗

    1. # -*- coding: utf-8 -*-#
    2. from bs4 import BeautifulSoup # 网页解析,获取数据
    3. import re # 正则表达式,进行文字匹配
    4. import urllib.request, urllib.error # 制定URL,获取网页数据
    5. def main():
    6. a = 1
    7. # 爬取网页,获取数据
    8. baseurl = "https://news.163.com/"
    9. Datelist, a = getDate(baseurl, a)
    10. savepath = ".\\新闻2.xls"
    11. saveDate(savepath, Datelist, a)
    12. # 得到指定URL的网页内容
    13. def askURL(url):
    14. head = {
    15. "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"}
    16. # 模拟浏览器头部信息,向服务器发送消息
    17. request = urllib.request.Request(url, headers=head)
    18. html = "" #字符串存
    19. try:
    20. response = urllib.request.urlopen(request)
    21. html = response.read().decode("utf-8", 'ignore')
    22. # print(html)
    23. except urllib.error.URLError as e:
    24. if hasattr(e, "code"):
    25. print(e.code)
    26. if hasattr(e, "reason"):
    27. print(e.reason)
    28. return html
    29. #爬网页
    30. def getDate(baseurl, a):
    31. datelist = [] #存为列表
    32. html = askURL(baseurl)
    33. soup = BeautifulSoup(html, "html.parser")
    34. for item in soup.select(".hidden"): # 查找符合要求的字符串,形成列表
    35. for c in item.select('a'):
    36. print(c)
    37. return datelist, a
    38. #保存
    39. def saveDate(savepath, Datelist, a):
    40. print("...")
    41. if __name__ == "__main__":
    42. main()

     四、保存数据

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

    1. # -*- coding: utf-8 -*-#
    2. from bs4 import BeautifulSoup # 网页解析,获取数据
    3. import re # 正则表达式,进行文字匹配
    4. import urllib.request, urllib.error # 制定URL,获取网页数据
    5. import xlwt # 进行excel操作
    6. def main():
    7. a = 1
    8. # 爬取网页,获取数据
    9. baseurl = "https://news.163.com/"
    10. Datelist, a = getDate(baseurl, a)
    11. savepath = "新闻2.xls"
    12. saveDate(savepath, Datelist, a)
    13. # 得到指定URL的网页内容
    14. def askURL(url):
    15. head = {
    16. "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"}
    17. # 模拟浏览器头部信息,向服务器发送消息
    18. request = urllib.request.Request(url, headers=head)
    19. html = "" #字符串存
    20. try:
    21. response = urllib.request.urlopen(request)
    22. html = response.read().decode("utf-8", 'ignore')
    23. # print(html)
    24. except urllib.error.URLError as e:
    25. if hasattr(e, "code"):
    26. print(e.code)
    27. if hasattr(e, "reason"):
    28. print(e.reason)
    29. return html
    30. findlink = re.compile(r'')
    31. #爬网页
    32. def getDate(baseurl, a):
    33. datelist = [] #存为列表
    34. html = askURL(baseurl)
    35. soup = BeautifulSoup(html, "html.parser")
    36. for item in soup.select(".hidden"): # 查找符合要求的字符串,形成列表
    37. for c in item.select('a'):
    38. #print(c)
    39. date = []
    40. c = str(c)
    41. Js = findjs.findall(c)
    42. date.append(Js)
    43. Link = findlink.findall(c)
    44. date.append(Link[0])
    45. date.append('')
    46. Html = askURL(Link[0])
    47. Soup = BeautifulSoup(Html, "html.parser")
    48. for item1 in Soup.select(".post_body"):
    49. date.insert(2, item1.get_text().strip())
    50. print("已保存第%.3d条新闻数据" % a)
    51. a += 1
    52. datelist.append(date)
    53. return datelist, a
    54. #保存
    55. def saveDate(savepath, Datelist, a):
    56. book = xlwt.Workbook(encoding="utf-8", style_compression=0) # 创建workbook对象
    57. sheet = book.add_sheet(savepath, cell_overwrite_ok=True) # 创建工作表
    58. crl = ("新闻标题", "新闻链接", "新闻内容")
    59. for i in range(0, len(crl)):
    60. sheet.write(0, i, crl[i])
    61. for i in range(1, a):
    62. for j in range(0, len(crl)):
    63. sheet.write(i, j, Datelist[i - 1][j])
    64. print("保存完毕")
    65. book.save(savepath)
    66. if __name__ == "__main__":
    67. main()

    词云图

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

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

    再进一步

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

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

    写在最后

    👍🏻点赞,你的认可是我创作的动力!

    ⭐收藏,你的青睐是我努力的方向!

    ✏️评论,你的意见是我进步的财富!

  • 相关阅读:
    golang及beego框架单元测试小结
    AI:原来Nacos还能这么玩儿
    RabbitMQ应用场景
    java中word转pdf/word转图片/word转html/html转word等操作
    Linux安装Nexus(图文解说详细版)
    【JavaWeb】Servlet系列——使用纯Servlet做一个单表的CRUD操作(实际操作实现篇)
    阿里P8架构师Spring源码阅读心得,都记录在这份PDF文档里面了
    (一)关于POE供电定义以及级别划分,如何测试网线是否满足相关标准?
    《探索网校 App 的魅力世界:知识与科技的完美结合》
    牛顿定理和相关推论
  • 原文地址:https://blog.csdn.net/m0_73222051/article/details/127621299