欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > python爬取B站弹幕评论

python爬取B站弹幕评论

2024/10/23 23:31:23 来源:https://blog.csdn.net/weixin_51891232/article/details/143085969  浏览:    关键词:python爬取B站弹幕评论

方式1:

进入B站,找到想爬取的视频

哔哩哔哩 (゜-゜)つロ 干杯~-bilibili

以为闲鱼梦想家这位up视频为例子天冷了小伙在北京出租屋吃涮羊肉,太香太开心了_哔哩哔哩_bilibili

 获取url

"https://www.bilibili.com/video/BV1feyNYcE36/?spm_id_from=333.880.my_history.page.click&vd_source=59cb1d172d45483d3059d3df82cd74b6"

在URL,bilibili前面j插入一个i,进入一个新天地

可以看到有弹幕地址,我们使用该URL

定义请求的 URL

# 定义请求的 URL
url = "https://api.bilibili.com/x/v1/dm/list.so?oid=26331385792"

 添加 User-Agent 头

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0"
}

 鼠标右键,检查:

 完整代码:

import requests
import re
# 方式1:
# 定义请求的 URL
url = "https://api.bilibili.com/x/v1/dm/list.so?oid=26331385792"# 添加 User-Agent 头
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0"
}# 发送 GET 请求
response = requests.get(url=url, headers=headers)# 设置响应编码
response.encoding = 'UTF-8'# 使用正则表达式提取弹幕内容
content_list = re.findall('<d p=".*?">(.*?)</d>', response.text)# 合并弹幕内容为一个字符串
content = '\n'.join(content_list)# 写入文件
with open('file01.txt', mode='a', encoding='utf-8') as f:f.write(content + '\n')  # 添加换行符以便分隔不同次写入# 打印弹幕内容
print(content)

方式2:(需要登录,想要获取其他日期时间的弹幕)

获取日期的URL

 https://api.bilibili.com/x/v2/dm/web/history/seg.so?type=1&oid=26331385792&date=2024-10-19

因为我们登录了,在headers里面加上我们的Cookie

完整代码:

import requests
import re# 方式2(查看历史日期信息):
for page in range(17,19):# 定义请求的 URLurl = f"https://api.bilibili.com/x/v2/dm/web/history/seg.so?type=1&oid=26331385792&date=2024-10-{page}"# 添加 User-Agent 头headers = {'cookie': "你的cookie","User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0"}# 发送 GET 请求response = requests.get(url=url, headers=headers)content_list = re.findall('[\u4e00-\u9fa5]+', response.text)# 打印弹幕内容print(f'2024-10-{page}')# 合并弹幕内容为一个字符串content = '\n'.join(content_list)print(content_list)# 写入文件with open('file02.txt', mode='a', encoding='utf-8') as f:f.write(f'2024-10-{page}'+ '\n'+ content + '\n')  # 添加换行符以便分隔不同次写入

 re.findall(...):这个函数返回在输入字符串中找到的所有匹配项,结果是一个列表。

+:表示匹配一个或多个前面的字符。

[\u4e00-\u9fa5]:这是一个字符类,匹配所有在这个范围内的中文字符。 

正则表达式:如果发现乱码,可以将该乱码内容提取到:在线正则表达式测试 进行转化 


可视化

可看https://blog.csdn.net/weixin_51891232/article/details/143022315,了解Matplotlib

import requests
import re
from collections import Counter
import matplotlib.pyplot as plt
import numpy as npcategories = []
values = []# 方式2(查看历史日期信息):
for page in range(17, 21):# 定义请求的 URLurl = f"https://api.bilibili.com/x/v2/dm/web/history/seg.so?type=1&oid=26331385792&date=2024-10-{page}"# 添加 User-Agent 头headers = {'cookie': "你的cookie","User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0"}# 发送 GET 请求response = requests.get(url=url, headers=headers)# 提取弹幕内容content_list = re.findall('[\u4e00-\u9fa5]+', response.text)print(f'2024-10-{page}')# 统计弹幕数量counter = Counter(content_list)# 获取前10名弹幕top_10 = counter.most_common(10)# 获取弹幕种类数量和总数量unique_count = len(counter)total_count = sum(counter.values())# 打印结果print("前10名弹幕及其数量:")for text, count in top_10:print(f"{text}: {count} 次")print(f"弹幕种类数量: {unique_count}")print(f"总数量: {total_count}")# 写入文件with open('file02.txt', mode='a', encoding='utf-8') as f:f.write(f'2024-10-{page}\n')f.write(f"前10名弹幕及其数量:\n")for text, count in top_10:f.write(f"{text}: {count} 次\n")f.write(f"弹幕种类数量: {unique_count}\n")f.write(f"总数量: {total_count}\n\n")# 数据categories.append(f'2024-10-{page}')values.append(total_count)# 绘制柱状图
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  # 显示中文标签# 创建柱状图
bars = plt.bar(categories, values, color='skyblue', width=0.5, alpha=0.7, linewidth=2)# 在每个柱顶上显示数量
for bar in bars:yval = bar.get_height()plt.text(bar.get_x() + bar.get_width()/2, yval, int(yval), ha='center', va='bottom')# 添加标题和标签
plt.title('弹幕总数量柱状图')
plt.xlabel('日期')
plt.ylabel('弹幕总数量')
# plt.axhline(0, color='black', linewidth=0.5, ls='--')  # 绘制x轴
# plt.axvline(0, color='black', linewidth=0.5, ls='--')  # 绘制y轴
# plt.grid()  # 添加网格
plt.show()  # 显示图形
  • yval = bar.get_height(): 获取当前柱子的高度,代表该柱的数值

  • plt.text(...): 在图表上添加文本,参数说明:

    • bar.get_x() + bar.get_width()/2: 计算柱子中心的 x 坐标,以便文本居中。

    • yval: y 坐标,文本将放置在柱子的顶端。

    • int(yval): 显示的文本内容,即柱子的高度。

    • ha='center': 水平对齐方式为中心对齐。

    • va='bottom': 垂直对齐方式为底部对齐,使文本位于柱子顶部。


词云图

import requests
import re
from collections import Counter
import matplotlib.pyplot as plt
from wordcloud import WordCloud# 初始化数据列表
pages = range(17, 21)
all_counters = []# 方式2(查看历史日期信息):
for page in pages:url = f"https://api.bilibili.com/x/v2/dm/web/history/seg.so?type=1&oid=26331385792&date=2024-10-{page}"headers = {'cookie': "你的cokkie","User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0"}response = requests.get(url=url, headers=headers)content_list = re.findall('[\u4e00-\u9fa5]+', response.text)# 统计弹幕数量counter = Counter(content_list)all_counters.append(counter)# 设置中文字体
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  # 显示中文标签# 创建子图
fig, axes = plt.subplots(2, 2, figsize=(10, 5))  # 根据需要调整子图数量和大小
axes = axes.flatten()  # 将子图展平,方便迭代plt.subplots_adjust(hspace=0.5, wspace=0.3)# 为每个日期生成词云
for i, counter in enumerate(all_counters):# 创建词云wordcloud = WordCloud(font_path='msyh.ttc',  # 替换为你的字体路径,确保支持中文width=500,height=300,background_color='white',).generate_from_frequencies(counter)# 绘制词云axes[i].imshow(wordcloud, interpolation='bilinear')axes[i].axis('off')  # 不显示坐标轴axes[i].set_title(f'2024-10-{pages[i]} 弹幕词云', fontsize=16)  # 设置标题# 调整布局
plt.tight_layout()
plt.show()

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com