0


Python爬虫以及数据可视化分析

Python爬虫以及数据可视化分析之Bilibili动漫排行榜信息爬取分析

简书地址:https://www.jianshu.com/u/40ac87350697

简单几步,通过Python对B站番剧排行数据进行爬取,并进行可视化分析

源码文件可以参考Github上传的项目:https://github.com/Lemon-Sheep/Py/tree/master

下面,我们开始吧!

PS: 作为Python爬虫初学者,如有不正确的地方,望各路大神不吝赐教[抱拳]

本项目将会对B站番剧排行的数据进行网页信息爬取以及数据可视化分析
image.png

首先,准备好相关库

requests、pandas、BeautifulSoup、matplotlib等

因为这是第三方库,所以我们需要额外下载
下载有两种方法(以requests为例,其余库的安装方法类似):

(一)在命令行输入

前提:装了pip( Python 包管理工具,提供了对Python 包的查找、下载、安装、卸载的功能。 )

pip install requests

(二)通过PyCharm下载

第一步:编译器左上角File–>Settings…
image.png
第二步:找到Project Interpreter 点击右上角加号按钮,弹出界面上方搜索库名:requests,点击左下角Install ,当提示successfully时,即安装完成。
2.png

image.png

准备工作做好后,开始项目的实行

一、获取网页内容

  1. def get_html(url):
  2. try:
  3. r = requests.get(url) # 使用get来获取网页数据
  4. r.raise_for_status() # 如果返回参数不为200,抛出异常
  5. r.encoding = r.apparent_encoding # 获取网页编码方式
  6. return r.text # 返回获取的内容
  7. except:
  8. return '错误'

我们来看爬取情况,是否有我们想要的内容:

  1. def main():
  2. url = 'https://www.bilibili.com/v/popular/rank/bangumi' # 网址
  3. html = get_html(url) # 获取返回值
  4. print(html) # 打印
  1. if __name__ == '__main__': #入口
  2. main()

爬取结果如下图所示:
image.png
成功!

二、信息解析阶段:

第一步,先构建BeautifulSoup实例

  1. soup = BeautifulSoup(html, 'html.parser') # 指定BeautifulSoup的解析器

第二步,初始化要存入信息的容器

  1. # 定义好相关列表准备存储相关信息
  2. TScore = [] # 综合评分
  3. name = [] # 动漫名字
  4. play= [] # 播放量
  5. review = [] # 评论数
  6. favorite= [] # 收藏数

第三步,开始信息整理
我们先获取番剧的名字,并将它们先存进列表中

  1. # ******************************************** 动漫名字存储
  2. for tag in soup.find_all('div', class_='info'):
  3. # print(tag)
  4. bf = tag.a.string
  5. name.append(str(bf))
  6. print(name)

此处我们用到了beautifulsoup的find_all()来进行解析。在这里,find_all()的第一个参数是标签名,第二个是标签中的class值(注意下划线哦(class_=‘info’))。

我们在网页界面按下F12,就能看到网页代码,找到相应位置,就能清晰地看见相关信息:
image.png

接着,我们用几乎相同的方法来对综合评分、播放量,评论数和收藏数来进行提取

  1. # ******************************************** 播放量存储
  2. for tag in soup.find_all('div', class_='detail'):
  3. # print(tag)
  4. bf = tag.find('span', class_='data-box').get_text()
  5. # 统一单位为‘万’
  6. if '亿' in bf:
  7. num = float(re.search(r'\d(.\d)?', bf).group()) * 10000
  8. # print(num)
  9. bf = num
  10. else:
  11. bf = re.search(r'\d*(\.)?\d', bf).group()
  12. play.append(float(bf))
  13. print(play)
  14. # ******************************************** 评论数存储
  15. for tag in soup.find_all('div', class_='detail'):
  16. # pl = tag.span.next_sibling.next_sibling
  17. pl = tag.find('span', class_='data-box').next_sibling.next_sibling.get_text()
  18. # *********统一单位
  19. if '万' not in pl:
  20. pl = '%.1f' % (float(pl) / 10000)
  21. # print(123, pl)
  22. else:
  23. pl = re.search(r'\d*(\.)?\d', pl).group()
  24. review.append(float(pl))
  25. print(review)
  26. # ******************************************** 收藏数
  27. for tag in soup.find_all('div', class_='detail'):
  28. sc = tag.find('span', class_='data-box').next_sibling.next_sibling.next_sibling.next_sibling.get_text()
  29. sc = re.search(r'\d*(\.)?\d', sc).group()
  30. favorite.append(float(sc))
  31. print(favorite)
  32. # ******************************************** 综合评分
  33. for tag in soup.find_all('div', class_='pts'):
  34. zh = tag.find('div').get_text()
  35. TScore.append(int(zh))
  36. print('综合评分', TScore)

其中有个.next_sibling是用于提取同级别的相同标签信息,如若没有这个方法,当它找到第一个’span’标签之后,就不会继续找下去了(根据具体情况来叠加使用此方法);
还用到了正则表达式来提取信息(需要导入库‘re’)

最后我们将提取的信息,存进excel表格之中,并返回结果集

  1. # 存储至excel表格中
  2. info = {'动漫名': name, '播放量(万)': play, '评论数(万)': review,'收藏数(万)': favorite, '综合评分': TScore}
  3. dm_file = pandas.DataFrame(info)
  4. dm_file.to_excel('Dongman.xlsx', sheet_name="动漫数据分析")
  5. # 将所有列表返回
  6. return name, play, review, favorite, TScore

我们可以打开文件看一看存储的信息格式(双击打开)
image.png
image.png
成功!

三、数据可视化分析

我们先做一些基础设置
要先准备一个文件: STHeiti Medium.ttc [注意存放在项目中的位置]
image.png

  1. my_font = font_manager.FontProperties(fname='./data/STHeiti Medium.ttc') # 设置中文字体(图表中能显示中文)
  2. # 为了坐标轴上能显示中文
  3. plt.rcParams['font.sans-serif'] = ['SimHei']
  4. plt.rcParams['axes.unicode_minus'] = False
  5. dm_name = info[0] # 番剧名
  6. dm_play = info[1] # 番剧播放量
  7. dm_review = info[2] # 番剧评论数
  8. dm_favorite = info[3] # 番剧收藏数
  9. dm_com_score = info[4] # 番剧综合评分
  10. # print(dm_com_score)

然后,开始使用matplot来绘制图形,实现数据可视化分析
文中有详细注释,这里就不再赘述了,聪明的你一定一看就懂了~

  1. # **********************************************************************综合评分和播放量对比
  2. # *******综合评分条形图
  3. fig, ax1 = plt.subplots()
  4. plt.bar(dm_name, dm_com_score, color='red') #设置柱状图
  5. plt.title('综合评分和播放量数据分析', fontproperties=my_font) # 表标题
  6. ax1.tick_params(labelsize=6)
  7. plt.xlabel('番剧名') # 横轴名
  8. plt.ylabel('综合评分') # 纵轴名
  9. plt.xticks(rotation=90, color='green') # 设置横坐标变量名旋转度数和颜色
  10. # *******播放量折线图
  11. ax2 = ax1.twinx() # 组合图必须加这个
  12. ax2.plot(dm_play, color='cyan') # 设置线粗细,节点样式
  13. plt.ylabel('播放量') # y轴
  14. plt.plot(1, label='综合评分', color="red", linewidth=5.0) # 图例
  15. plt.plot(1, label='播放量', color="cyan", linewidth=1.0, linestyle="-") # 图例
  16. plt.legend()
  17. plt.savefig(r'E:1.png', dpi=1000, bbox_inches='tight') #保存至本地
  18. plt.show()

来看看效果

有没有瞬间就感觉高上~~了(嘿嘿~)

然后我们用相同的方法来多绘制几个对比图:

  1. # **********************************************************************评论数和收藏数对比
  2. # ********评论数条形图
  3. fig, ax3 = plt.subplots()
  4. plt.bar(dm_name, dm_review, color='green')
  5. plt.title('番剧评论数和收藏数分析')
  6. plt.ylabel('评论数(万)')
  7. ax3.tick_params(labelsize=6)
  8. plt.xticks(rotation=90, color='green')
  9. # *******收藏数折线图
  10. ax4 = ax3.twinx() # 组合图必须加这个
  11. ax4.plot(dm_favorite, color='yellow') # 设置线粗细,节点样式
  12. plt.ylabel('收藏数(万)')
  13. plt.plot(1, label='评论数', color="green", linewidth=5.0)
  14. plt.plot(1, label='收藏数', color="yellow", linewidth=1.0, linestyle="-")
  15. plt.legend()
  16. plt.savefig(r'E:2.png', dpi=1000, bbox_inches='tight')
  17. # **********************************************************************综合评分和收藏数对比
  18. # *******综合评分条形图
  19. fig, ax5 = plt.subplots()
  20. plt.bar(dm_name, dm_com_score, color='red')
  21. plt.title('综合评分和收藏数量数据分析')
  22. plt.ylabel('综合评分')
  23. ax5.tick_params(labelsize=6)
  24. plt.xticks(rotation=90, color='green')
  25. # *******收藏折线图
  26. ax6 = ax5.twinx() # 组合图必须加这个
  27. ax6.plot(dm_favorite, color='yellow') # 设置线粗细,节点样式
  28. plt.ylabel('收藏数(万)')
  29. plt.plot(1, label='综合评分', color="red", linewidth=5.0)
  30. plt.plot(1, label='收藏数', color="yellow", linewidth=1.0, linestyle="-")
  31. plt.legend()
  32. plt.savefig(r'E:3.png', dpi=1000, bbox_inches='tight')
  33. # **********************************************************************播放量和评论数对比
  34. # *******播放量条形图
  35. fig, ax7 = plt.subplots()
  36. plt.bar(dm_name, dm_play, color='cyan')
  37. plt.title('播放量和评论数 数据分析')
  38. plt.ylabel('播放量(万)')
  39. ax7.tick_params(labelsize=6)
  40. plt.xticks(rotation=90, color='green')
  41. # *******评论数折线图
  42. ax8 = ax7.twinx() # 组合图必须加这个
  43. ax8.plot(dm_review, color='green') # 设置线粗细,节点样式
  44. plt.ylabel('评论数(万)')
  45. plt.plot(1, label='播放量', color="cyan", linewidth=5.0)
  46. plt.plot(1, label='评论数', color="green", linewidth=1.0, linestyle="-")
  47. plt.legend()
  48. plt.savefig(r'E:4.png', dpi=1000, bbox_inches='tight')
  49. plt.show()

我们来看看最终效果
image.png
image.png

Nice!很完美~ 大家可以根据自己的想法按照相同的方法进行数据组合分析。

最后,附上全部代码

  1. import re
  2. import pandas
  3. import requests
  4. from bs4 import BeautifulSoup
  5. import matplotlib.pyplot as plt
  6. from matplotlib import font_manager
  7. def get_html(url):
  8. try:
  9. r = requests.get(url) # 使用get来获取网页数据
  10. r.raise_for_status() # 如果返回参数不为200,抛出异常
  11. r.encoding = r.apparent_encoding # 获取网页编码方式
  12. return r.text # 返回获取的内容
  13. except:
  14. return '错误'
  15. def save(html):
  16. # 解析网页
  17. soup = BeautifulSoup(html, 'html.parser') # 指定Beautiful的解析器为“html.parser”
  18. with open('./data/B_data.txt', 'r+', encoding='UTF-8') as f:
  19. f.write(soup.text)
  20. # 定义好相关列表准备存储相关信息
  21. TScore = [] # 综合评分
  22. name = [] # 动漫名字
  23. bfl = [] # 播放量
  24. pls = [] # 评论数
  25. scs = [] # 收藏数
  26. # ******************************************** 动漫名字存储
  27. for tag in soup.find_all('div', class_='info'):
  28. # print(tag)
  29. bf = tag.a.string
  30. name.append(str(bf))
  31. print(name)
  32. # ******************************************** 播放量存储
  33. for tag in soup.find_all('div', class_='detail'):
  34. # print(tag)
  35. bf = tag.find('span', class_='data-box').get_text()
  36. # 统一单位为‘万’
  37. if '亿' in bf:
  38. num = float(re.search(r'\d(.\d)?', bf).group()) * 10000
  39. # print(num)
  40. bf = num
  41. else:
  42. bf = re.search(r'\d*(\.)?\d', bf).group()
  43. bfl.append(float(bf))
  44. print(bfl)
  45. # ******************************************** 评论数存储
  46. for tag in soup.find_all('div', class_='detail'):
  47. # pl = tag.span.next_sibling.next_sibling
  48. pl = tag.find('span', class_='data-box').next_sibling.next_sibling.get_text()
  49. # *********统一单位
  50. if '万' not in pl:
  51. pl = '%.1f' % (float(pl) / 10000)
  52. # print(123, pl)
  53. else:
  54. pl = re.search(r'\d*(\.)?\d', pl).group()
  55. pls.append(float(pl))
  56. print(pls)
  57. # ******************************************** 收藏数
  58. for tag in soup.find_all('div', class_='detail'):
  59. sc = tag.find('span', class_='data-box').next_sibling.next_sibling.next_sibling.next_sibling.get_text()
  60. sc = re.search(r'\d*(\.)?\d', sc).group()
  61. scs.append(float(sc))
  62. print(scs)
  63. # ******************************************** 综合评分
  64. for tag in soup.find_all('div', class_='pts'):
  65. zh = tag.find('div').get_text()
  66. TScore.append(int(zh))
  67. print('综合评分', TScore)
  68. # 存储至excel表格中
  69. info = {'动漫名': name, '播放量(万)': bfl, '评论数(万)': pls, '收藏数(万)': scs, '综合评分': TScore}
  70. dm_file = pandas.DataFrame(info)
  71. dm_file.to_excel('Dongman.xlsx', sheet_name="动漫数据分析")
  72. # 将所有列表返回
  73. return name, bfl, pls, scs, TScore
  74. def view(info):
  75. my_font = font_manager.FontProperties(fname='./data/STHeiti Medium.ttc') # 设置中文字体(图标中能显示中文)
  76. dm_name = info[0] # 番剧名
  77. dm_play = info[1] # 番剧播放量
  78. dm_review = info[2] # 番剧评论数
  79. dm_favorite = info[3] # 番剧收藏数
  80. dm_com_score = info[4] # 番剧综合评分
  81. # print(dm_com_score)
  82. # 为了坐标轴上能显示中文
  83. plt.rcParams['font.sans-serif'] = ['SimHei']
  84. plt.rcParams['axes.unicode_minus'] = False
  85. # **********************************************************************综合评分和播放量对比
  86. # *******综合评分条形图
  87. fig, ax1 = plt.subplots()
  88. plt.bar(dm_name, dm_com_score, color='red') #设置柱状图
  89. plt.title('综合评分和播放量数据分析', fontproperties=my_font) # 表标题
  90. ax1.tick_params(labelsize=6)
  91. plt.xlabel('番剧名') # 横轴名
  92. plt.ylabel('综合评分') # 纵轴名
  93. plt.xticks(rotation=90, color='green') # 设置横坐标变量名旋转度数和颜色
  94. # *******播放量折线图
  95. ax2 = ax1.twinx() # 组合图必须加这个
  96. ax2.plot(dm_play, color='cyan') # 设置线粗细,节点样式
  97. plt.ylabel('播放量') # y轴
  98. plt.plot(1, label='综合评分', color="red", linewidth=5.0) # 图例
  99. plt.plot(1, label='播放量', color="cyan", linewidth=1.0, linestyle="-") # 图例
  100. plt.legend()
  101. plt.savefig(r'E:1.png', dpi=1000, bbox_inches='tight') #保存至本地
  102. # plt.show()
  103. # **********************************************************************评论数和收藏数对比
  104. # ********评论数条形图
  105. fig, ax3 = plt.subplots()
  106. plt.bar(dm_name, dm_review, color='green')
  107. plt.title('番剧评论数和收藏数分析')
  108. plt.ylabel('评论数(万)')
  109. ax3.tick_params(labelsize=6)
  110. plt.xticks(rotation=90, color='green')
  111. # *******收藏数折线图
  112. ax4 = ax3.twinx() # 组合图必须加这个
  113. ax4.plot(dm_favorite, color='yellow') # 设置线粗细,节点样式
  114. plt.ylabel('收藏数(万)')
  115. plt.plot(1, label='评论数', color="green", linewidth=5.0)
  116. plt.plot(1, label='收藏数', color="yellow", linewidth=1.0, linestyle="-")
  117. plt.legend()
  118. plt.savefig(r'E:2.png', dpi=1000, bbox_inches='tight')
  119. # **********************************************************************综合评分和收藏数对比
  120. # *******综合评分条形图
  121. fig, ax5 = plt.subplots()
  122. plt.bar(dm_name, dm_com_score, color='red')
  123. plt.title('综合评分和收藏数量数据分析')
  124. plt.ylabel('综合评分')
  125. ax5.tick_params(labelsize=6)
  126. plt.xticks(rotation=90, color='green')
  127. # *******收藏折线图
  128. ax6 = ax5.twinx() # 组合图必须加这个
  129. ax6.plot(dm_favorite, color='yellow') # 设置线粗细,节点样式
  130. plt.ylabel('收藏数(万)')
  131. plt.plot(1, label='综合评分', color="red", linewidth=5.0)
  132. plt.plot(1, label='收藏数', color="yellow", linewidth=1.0, linestyle="-")
  133. plt.legend()
  134. plt.savefig(r'E:3.png', dpi=1000, bbox_inches='tight')
  135. # **********************************************************************播放量和评论数对比
  136. # *******播放量条形图
  137. fig, ax7 = plt.subplots()
  138. plt.bar(dm_name, dm_play, color='cyan')
  139. plt.title('播放量和评论数 数据分析')
  140. plt.ylabel('播放量(万)')
  141. ax7.tick_params(labelsize=6)
  142. plt.xticks(rotation=90, color='green')
  143. # *******评论数折线图
  144. ax8 = ax7.twinx() # 组合图必须加这个
  145. ax8.plot(dm_review, color='green') # 设置线粗细,节点样式
  146. plt.ylabel('评论数(万)')
  147. plt.plot(1, label='播放量', color="cyan", linewidth=5.0)
  148. plt.plot(1, label='评论数', color="green", linewidth=1.0, linestyle="-")
  149. plt.legend()
  150. plt.savefig(r'E:4.png', dpi=1000, bbox_inches='tight')
  151. plt.show()
  152. def main():
  153. url = 'https://www.bilibili.com/v/popular/rank/bangumi' # 网址
  154. html = get_html(url) # 获取返回值
  155. # print(html)
  156. info = save(html)
  157. view(info)
  158. if __name__ == '__main__':
  159. main()

关于图表的分析和得出的结论,这里就不描述了,一千个读者就有一千个哈姆雷特,每个人有每个人的分析描述方法,相信你们能有更加透彻的见解分析。

以上就是关于爬虫以及数据可视化分析的内容,希望能帮到你们!
伙伴们可以到github上查看源码文件:https://github.com/Lemon-Sheep/Py/tree/master

喜欢记得点个赞哦~

标签: python 爬虫 可视化

本文转载自: https://blog.csdn.net/Jacompol/article/details/111692298
版权归原作者 三秋树&二月花 所有, 如有侵权,请联系我们删除。

“Python爬虫以及数据可视化分析”的评论:

还没有评论