当前位置: 首页 > 后端技术 > Python

你同意《后浪》

时间:2023-03-26 13:40:43 Python

前几天在哔哩哔哩上线了一个小视频《后浪》,在全网引起热烈反响,褒贬不一。视频地址为:https://www.bilibili.com/video/BV1FV411d7u7。本篇我们将抓取视频弹幕,了解B站网友对视频的看法。视频弹幕存在于xml文件中。链接格式为:http://comment.bilibili.com/+cid+.xml。我们只需要获取视频的cid即可。让我们看看如何获??得它。我们先打开视频。链接到https://www.bilibili.com/video/BV1FV411d7u7,然后按F12键打开开发者工具选择Network,然后刷新页面,我们就可以在Filter里面输入cid了,如下图:得到cid,我们可以知道弹幕文件链接是:http://comment.bilibili.com/186803402.xml,打开链接看看:弹幕爬取的实现代码如下:url="http://comment.bilibili.com/186803402.xml"req=requests.get(url)html=req.contenthtml_doc=str(html,"utf-8")#改为utf-8#解析soup=BeautifulSoup(html_doc,"lxml")结果=汤。find_all('d')contents=[x.textforxinresults]#保存结果dic={"contents":contents}df=pd.DataFrame(dic)df["contents"].to_csv("bili.csv",encoding="utf-8",index=False)现在我们已经获取到了弹幕数据,接下来我们将数据做一个词云展示,实现代码如下:defjieba_():#打开评论数据文件content=open("bili.csv","rb").read()#jieba分词word_list=jieba.cut(content)words=[]#过滤掉的词stopwords=open("stopwords.txt","r",encoding="utf-8").read().split("\n")[:-1]forwordinword_list:如果单词不在停用词中:words.append(word)globalword_cloud#用逗号分隔单词word_cloud=','.join(words)defcloud():#打开词云背景图cloud_mask=np.array(Image.open("bg.png"))#定义部分词云attributewc=WordCloud(#背景图片分割颜色为白色background_color='white',#背景图案mask=cloud_mask,#显示最大字数max_words=500,#显示中文font_path='./fonts/simhei.ttf',#最大尺寸max_font_size=60,repeat=True)globalword_cloud#词云函数x=wc.generate(word_cloud)#生成词云图像image=x.to_image()#显示词云图像image.show()#保存词云图片wc.to_file('cloud.png')看效果:源码可在公众号Python小二后台回复200509获取。