python爬取b站视频评论
时间: 2023-10-08 08:11:31 浏览: 30
要爬取b站视频评论,可以使用Python中的requests模块发送网络请求,然后使用正则表达式或者BeautifulSoup等库来解析HTML页面,从而获取评论内容。
以下是一个简单的示例代码:
```python
import requests
import re
from bs4 import BeautifulSoup
# 视频页面的URL
url = 'https://www.bilibili.com/video/BV1Cx411o7kn'
# 发送网络请求
response = requests.get(url)
# 解析HTML页面
soup = BeautifulSoup(response.text, 'html.parser')
# 获取评论区的URL
comment_url = soup.find('div', {'id': 'comment'})['data-src']
# 发送评论区的网络请求
response = requests.get(comment_url)
# 解析评论区的HTML页面
soup = BeautifulSoup(response.text, 'html.parser')
# 获取所有评论
comments = soup.find_all('div', {'class': 'comment'})
# 打印每个评论的用户名和内容
for comment in comments:
author = comment.find('a', {'class': 'name'}).text
content = comment.find('div', {'class': 'text'}).text.strip()
print(f'{author}: {content}')
```
需要注意的是,为了爬取评论区的内容,需要先获取评论区的URL。在b站的视频页面中,评论区的URL存储在一个`<div>`标签的`data-src`属性中。