python爬取豆瓣电影评论
时间: 2023-10-04 08:13:30 浏览: 27
好的,以下是一个简单的Python爬取豆瓣电影评论的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 豆瓣电影评论页面url
url = 'https://movie.douban.com/subject/26752088/comments'
# 请求头,模拟浏览器发送请求
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299'
}
# 发送get请求,获取页面内容
response = requests.get(url, headers=headers)
# 使用BeautifulSoup解析html页面
soup = BeautifulSoup(response.text, 'html.parser')
# 获取所有评论区域的div
comments = soup.find_all('div', class_='comment-item')
# 遍历评论区域,提取评论及评分信息
for comment in comments:
# 提取评论信息
comment_content = comment.find('span', class_='short').text.strip()
print('评论内容:', comment_content)
# 提取评分信息
rating = comment.find('span', class_='rating')
if rating is not None:
rating_value = rating.attrs['class'][0][-2:]
print('评分:', rating_value)
print('---------------------')
```
该代码使用requests库发送get请求获取豆瓣电影评论页面,使用BeautifulSoup库解析页面内容,提取评论和评分信息,并打印输出。需要注意的是,需要设置请求头来模拟浏览器发送请求,否则可能会被豆瓣反爬虫机制封禁。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)