python爬虫爬取豆瓣评论
时间: 2023-10-11 19:07:52 浏览: 74
好的,以下是一个简单的爬取豆瓣评论的Python代码示例:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://movie.douban.com/subject/{电影ID}/comments?start={页数}&limit=20&sort=new_score&status=P'
# 电影ID和页数需要根据实际情况填写
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
# 找到评论所在的div标签
comments = soup.select('.comment-item > p')
# 循环输出每条评论
for comment in comments:
print(comment.get_text())
```
需要注意的是,爬取豆瓣评论需要登录账号,并且豆瓣有反爬虫机制,如果频繁爬取可能会被封IP。建议使用代理IP和随机User-Agent来规避风险。另外,在爬取评论时,要遵守网站的规则,不要进行非法操作。
相关问题
python爬虫爬取豆瓣评论页
要爬取豆瓣评论页,可以使用Python的爬虫技术结合相关库来实现。可以按照以下步骤进行操作:
1. 首先,导入所需的库,如requests、BeautifulSoup和pandas。
2. 使用requests库向豆瓣评论页发送HTTP请求,获取页面的HTML内容。
3. 使用BeautifulSoup库解析HTML内容,提取所需的评论数据。
4. 将评论数据保存到Excel文件中,可以使用pandas库来处理和导出数据。
下面是一个示例代码,展示了如何爬取豆瓣评论页并保存到Excel文件中:
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
# 发送HTTP请求获取页面内容
url = 'https://movie.douban.com/subject/1292052/comments?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'}
response = requests.get(url, headers=headers)
html_content = response.text
# 解析HTML内容,提取评论数据
soup = BeautifulSoup(html_content, 'html.parser')
comments = soup.find_all(class_='comment-item')
data = []
for comment in comments:
username = comment.find(class_='comment-info').find('a').text.strip()
rating = comment.find(class_='rating').attrs['class'][0].replace('allstar', '')
content = comment.find(class_='short').text.strip()
data.append([username, rating, content])
# 将数据保存到Excel文件中
df = pd.DataFrame(data, columns=['Username', 'Rating', 'Content'])
df.to_excel('douban_comments.xlsx', index=False)
```
python爬虫爬取豆瓣阅读
以下是一个使用Python爬虫爬取豆瓣阅读的示例:
1. 创建爬虫文件
在命令行中使用命令工具生成一个名为db_book的爬虫文件,该文件将用于爬取豆瓣阅读的数据。
2. 修改爬虫文件
在生成的爬虫文件(./spiders/db_book.py)中,修改parse方法如下:
```python
def parse(self, response):
file_name = 'douban_python'
with open(file_name, 'wb') as f:
f.write(response.body)
```
这段代码将爬取到的数据保存到名为douban_python的文件中。
3. 运行爬虫
运行爬虫文件,开始爬取豆瓣阅读的数据。
以上是一个简单的示例,你可以根据自己的需求进行进一步的修改和扩展。