python爬取豆瓣电影影评
时间: 2023-10-02 15:05:56 浏览: 97
您可以使用Python中的爬虫库(如Requests)和解析库(如BeautifulSoup)来爬取豆瓣电影影评。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
def get_movie_reviews(movie_url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0;Win64) AppleWebkit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'
}
# 发送请求获取页面内容
response = requests.get(movie_url, headers=headers)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
review_tags = soup.find_all('div', class_='comment-item')
for tag in review_tags:
# 获取评论内容
review = tag.find('span', class_='short').text.strip()
print(review)
else:
print("请求失败")
# 示例电影链接:肖申克的救赎
movie_url = 'https://movie.douban.com/subject/1292052/comments?status=P'
get_movie_reviews(movie_url)
```
在上述示例代码中,我们使用了`requests`库发送HTTP请求,设置了合适的`User-Agent`头信息以模拟浏览器访问。然后我们使用`BeautifulSoup`库解析HTML页面,提取了影评内容并打印输出。您可以根据自己的需求进行进一步处理和存储。不过请注意,爬取网站时请尊重网站的使用规则,避免频繁请求和对服务器造成过大负载。