爬取豆瓣电影影评
时间: 2025-06-14 19:47:38 浏览: 14
### 爬取豆瓣电影影评的技术指导
爬取豆瓣电影影评需要结合网络请求库(如 `requests` 或 `httpx`)和解析工具(如 `BeautifulSoup` 或 `lxml`)。以下是一个完整的示例代码,展示如何爬取豆瓣电影影评并保存到本地文件。
#### 1. 准备工作
在开始之前,请确保安装了所需的库:
```bash
pip install requests beautifulsoup4
```
#### 2. 请求与解析
以下是实现爬取豆瓣影评的完整代码:
```python
import requests
from bs4 import BeautifulSoup
# 设置请求头以模拟浏览器访问
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
# 存储所有影评的列表
all_reviews = []
# 循环爬取多页数据
for page in range(0, 10): # 假设爬取前10页
url = f"https://movie.douban.com/subject/1291549/comments?start={page * 20}&limit=20&status=P&sort=new_score"
response = requests.get(url, headers=headers)
if response.status_code != 200:
print(f"Failed to fetch page {page}. Status code: {response.status_code}")
continue
soup = BeautifulSoup(response.text, "html.parser")
# 查找影评内容
comments = soup.find_all("div", class_="comment") # 定位影评块
for comment in comments:
username = comment.find("span", class_="comment-info").a.get_text(strip=True) # 用户名
review = comment.find("span", class_="short").get_text(strip=True) # 影评内容
all_reviews.append({"username": username, "review": review})
# 将结果保存到文件
with open("douban_reviews.txt", "w", encoding="utf-8") as file:
for review in all_reviews:
file.write(f"Username: {review['username']}\nReview: {review['review']}\n{'-'*40}\n")
print(f"成功爬取并保存了 {len(all_reviews)} 条影评。")
```
#### 3. 注意事项
- 豆瓣网站可能对频繁请求进行限制,建议在每次请求后添加延迟以避免被封禁[^1]。
- 使用 `time.sleep()` 方法来控制请求频率:
```python
import time
time.sleep(2) # 每次请求后等待2秒
```
- 如果需要处理登录状态或验证码,可以考虑使用 `selenium` 或其他自动化工具[^1]。
#### 4. 数据存储
上述代码将爬取的影评保存为文本文件。如果需要更复杂的存储方式,例如保存为 JSON 格式,可以修改保存逻辑:
```python
import json
with open("douban_reviews.json", "w", encoding="utf-8") as file:
json.dump(all_reviews, file, ensure_ascii=False, indent=4)
```
阅读全文
相关推荐


















