python爬取豆瓣电影评论
时间: 2023-09-11 11:04:34 浏览: 59
好的,以下是一个简单的 Python 爬取豆瓣电影评论的代码示例:
```python
import requests
from bs4 import BeautifulSoup
# 豆瓣电影链接
url = 'https://movie.douban.com/subject/26794435/comments?start=0&limit=20&sort=new_score&status=P'
# 请求头,模拟浏览器访问
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.3'}
# 发送 GET 请求,获取网页 HTML
response = requests.get(url, headers=headers)
html = response.text
# 使用 BeautifulSoup 解析 HTML
soup = BeautifulSoup(html, 'html.parser')
# 获取评论列表
comments = soup.select('.comment-item')
# 循环遍历每条评论,提取信息并输出
for comment in comments:
# 提取用户名
username = comment.select('.comment-info a')[0].get_text()
# 提取评论时间
time = comment.select('.comment-time ')[0].get_text()
# 提取评论内容
content = comment.select('.short')[0].get_text()
# 输出信息
print('用户名:', username)
print('时间:', time)
print('评论:', content)
print('------------------------')
```
这段代码可以爬取豆瓣电影《摔跤吧!爸爸》的评论,你可以根据自己需要修改链接和选择器,来爬取其他电影的评论。另外,需要注意的是,豆瓣网站有反爬机制,如果频繁爬取可能会被封 IP,建议适当控制访问频率。
相关推荐
![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)