数据分析(微博热搜榜单热度排名)

利用上次爬取的微博热搜榜单进行改进,对微博热搜榜单进行数据分析,额外爬取了榜单的热度值

本次实现的主要问题在于图像的正确表现上

一是对于字符串在图表上如何实现,另一是标题字符串过长的问题

对于字符串的写入,采用了先绘制不带字符串的图表,在将相应字体(字体在电脑的fonts文件夹下选择)的字符串配置到x轴

配置完成后,因为字符串过长而重叠,所有使用rotation=90讲使字符串垂直写入

此时字符串长度还是超出了界面,所以设置bottom(底面)的值使字符串完整显示

代码如下:

import requests
from bs4 import BeautifulSoup
from matplotlib import pyplot as plt
from matplotlib import font_manager
#配置字体
my_font=font_manager.FontProperties(fname=‘C:\Windows\Fonts\SIMLI.TTF‘)
r=requests.get(‘https://s.weibo.com/top/summary‘)
soup=BeautifulSoup(r.text,‘html.parser‘)
a=soup.find_all(‘td‘,‘td-02‘)
t=[]
s=[]
for i in a[1:]:
i=i.contents
t.append(list(i)[1].string)#标题
s.append(int(list(i)[3].string))#热度值
plt.figure(figsize=(15,10))
plt.subplots_adjust(bottom=0.45)#调整下底
plt.bar(range(len(t)),s)#绘制图表
plt.xticks(range(len(t)),t,fontproperties=my_font,rotation=90)#配置字符串
plt.show()

效果如下

数据分析(微博热搜榜单热度排名)

 榜单是实时更新的,所有你在不同时候运行程序将得到不同的数据

本次的设计主要是学会了在图表中字符串的处理,以及在爬取过程中加深对HTML代码的理解和认识

相关推荐