本文中的代码主要功能是从指定的 B 站视频链接中提取评论,并将其保存到一个文本文件中。用户可以指定需要爬取的页面次数以及保存的文件名。代码使用了 DrissionPage
库,这是一种基于 Selenium 和 Requests 的高层次网页抓取工具,支持异步请求和网络流监听。用户可以根据需要调整爬取的页面数量和保存的文件名,以满足特定的需求。
python">from DrissionPage import ChromiumPage # pip install DrissionPage
import time
import jsonURL = input("请输入B站视频链接:")
num = int(input("请输入要爬取的页面次数:"))
name = input("请输入要保存的文件名:")
name = name + '.txt'page = ChromiumPage()
page.set.load_mode.none()# 监听特定的网络流
page.listen.start('https://api.bilibili.com/x/v2/reply/wbi/main?')# 访问B站页面
page.get(f'{URL}')
time.sleep(3)for _ in range(num + 1):page.scroll.to_bottom()print("正在爬取第{0}页评论".format(_ + 1))time.sleep(2)# 用于存储所有捕获的响应数据
responses = []try:# 循环监听直到达到所需数量或超时for _ in range(num):# 等待网络请求包到达packet = page.listen.wait(timeout=10)# 停止加载页面(这步可以根据需求调整)page.stop_loading()# 接收 HTTP 响应内容response_body = packet.response.body# 将响应内容存储到列表中responses.append(response_body)time.sleep(1)except Exception as e:print(f"解析出现错误: {e}")# 处理和打印捕获到的所有响应
total_comments = 0with open(name, 'a', encoding='utf-8') as file:for response in responses:try:if 'data' in response:datas = response['data']['replies']total_comments += len(datas)for data in datas:comments = data['content']['message']uname = data['member']['uname']sex = data['member']['sex']IP = data['reply_control']['location']# print(f"评论内容: {comments}\n用户名: {uname}\n性别: {sex}\nIP地址: {IP}\n")file.write(json.dumps(f"评论内容: {comments}, 用户名: {uname}, 性别: {sex}, IP地址: {IP}", ensure_ascii=False, indent=4))file.write('\n')except KeyError as e:print(f"处理响应时出现错误: {e}")page.close()# 最后打印总评论数量
print(f"总评论数量: {total_comments}")