python爬虫爬取电影评论
时间: 2025-02-13 18:09:05 浏览: 43
### 使用Python编写爬虫程序抓取电影评论
#### 准备工作
在开始之前,确保安装了必要的库。可以使用`pip install requests beautifulsoup4 pandas openpyxl`命令来安装所需的包。
#### 获取网页内容
通过发送HTTP请求获取目标网站页面的内容。这里以豆瓣网为例:
```python
import requests
from bs4 import BeautifulSoup
url = "https://movie.douban.com/subject/{movie_id}/comments".format(movie_id="example_movie_id") # 替换为实际电影ID
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
}
response = requests.get(url=url, headers=headers)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
else:
print('Failed to get the page.')
```
此部分代码用于构建访问特定电影评论页的URL并发起GET请求,同时设置了浏览器代理头信息防止被封禁[^1]。
#### 解析HTML文档结构
利用BeautifulSoup解析返回的数据流,定位到包含评论的具体标签位置:
```python
comment_divs = soup.find_all('div', class_='comment') # 查找所有的评论容器节点
for div in comment_divs[:]:
try:
user_name = div.select_one('.comment-info a').get_text(strip=True)
rating = int(div.select_one('.rating')['class'][0][-2]) if div.select_one('.rating') else None
content = div.p.string.strip()
item = {'用户名': user_name,
'评分星级': rating,
'评论正文': content}
yield item
except Exception as e:
continue
```
上述代码片段展示了如何提取每条评论中的用户名、打分以及具体内容,并将其封装成字典形式以便后续处理[^3]。
#### 数据存储
最后一步就是把收集好的数据保存下来,通常会采用CSV文件格式方便日后读取查看:
```python
import csv
with open('./douban_comments.csv', mode='w', newline='', encoding='utf-8-sig') as file:
writer = csv.writer(file)
header = ['用户名', '评分星级', '评论正文']
writer.writerow(header)
for record in records_generator():
row = [record[field] for field in header]
writer.writerow(row)
```
这段脚本实现了将先前定义好的记录列表逐行写入CSV文件的功能[^2]。
阅读全文
相关推荐















