Python爬虫实战:解析B站视频弹幕和评论并生成词云图
以下是用Python编写的爬取弹幕和评论,并绘制词云图的代码:
import requests
from bs4 import BeautifulSoup
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 爬取网页源代码
url = 'https://www.bilibili.com/video/BV1MN41187U6/?spm_id_from=333.337.search-card.all.click'
response = requests.get(url)
html = response.text
# 解析网页源代码
soup = BeautifulSoup(html, 'html.parser')
# 查找弹幕标签或类名
danmu_tag = soup.find('div', class_='danmu-list')
# 检查标签或类名是否正确
if danmu_tag is None:
print('未找到弹幕标签或类名')
exit()
# 查找评论标签或类名
comment_tag = soup.find('div', class_='comment-list')
# 检查标签或类名是否正确
if comment_tag is None:
print('未找到评论标签或类名')
exit()
# 获取弹幕文本
danmu_text = danmu_tag.get_text()
# 获取评论文本
comment_text = comment_tag.get_text()
# 分词
danmu_words = jieba.cut(danmu_text)
comment_words = jieba.cut(comment_text)
# 合并分词结果
danmu_words = ' '.join(danmu_words)
comment_words = ' '.join(comment_words)
# 生成弹幕词云图
danmu_wordcloud = WordCloud(font_path='SimHei.ttf').generate(danmu_words)
# 生成评论词云图
comment_wordcloud = WordCloud(font_path='SimHei.ttf').generate(comment_words)
# 显示弹幕词云图
plt.imshow(danmu_wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
# 显示评论词云图
plt.imshow(comment_wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
请注意,运行此代码前需要安装以下库:
- requests
- beautifulsoup4
- jieba
- wordcloud
- matplotlib
另外,代码中的SimHei.ttf是用于绘制中文词云图的字体文件,请确保该文件存在。如果没有该字体文件,可以将font_path参数设置为其他可用的中文字体文件路径。
原文地址: https://www.cveoy.top/t/topic/qzQj 著作权归作者所有。请勿转载和采集!