python爬取豆瓣评论
时间: 2023-10-04 17:13:28 浏览: 161
以下是使用Python爬取豆瓣电影评论的示例:
1. 首先,我们需要导入需要的库,包括requests、BeautifulSoup和re:
```python
import requests
from bs4 import BeautifulSoup
import re
```
2. 接下来,我们需要获取要爬取的电影的URL和评论的页数:
```python
url = 'https://movie.douban.com/subject/34841067/comments?start=0&limit=20&status=P&sort=new_score'
page_num = 5 # 想爬取的评论页数
```
3. 然后,我们可以编写一个函数来获取每一页的评论:
```python
def get_comments(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36'
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
comments = soup.find_all('span', class_='short')
return comments
```
上面的函数使用了requests库来获取HTML页面,然后使用BeautifulSoup库来解析HTML页面并获取评论。我们将评论存储在一个列表中并返回。
4. 接下来,我们可以编写一个函数来获取所有评论:
```python
def get_all_comments(url, page_num):
all_comments = []
for i in range(page_num):
start_num = i * 20
url = re.sub('start=\d+', 'start={}'.format(start_num), url)
comments = get_comments(url)
all_comments.extend(comments)
return all_comments
```
上面的函数使用了一个for循环来获取所有的评论,它首先从第一页开始,然后逐个增加页面号并获取每一页的评论。最后,它将所有的评论存储在一个列表中并返回。
5. 最后,我们可以调用get_all_comments函数来获取所有评论:
```python
all_comments = get_all_comments(url, page_num)
for comment in all_comments:
print(comment.text)
```
上面的代码将打印所有的评论文本。
阅读全文
相关推荐


















