python爬虫获取豆瓣评分
时间: 2025-02-07 08:07:14 浏览: 56
### 使用Python编写爬虫程序抓取豆瓣电影评分
为了实现这一目标,可以采用`requests`库发送HTTP请求以及`BeautifulSoup`解析HTML文档。以下是具体方法:
#### 准备工作
确保已安装必要的Python包,可通过pip命令安装这些依赖项:
```bash
pip install requests beautifulsoup4 lxml openpyxl
```
#### 抓取页面内容
利用`requests.get()`函数向目标URL发起GET请求,并获取响应体中的HTML源码。
```python
import requests
from bs4 import BeautifulSoup
url = 'https://movie.douban.com/top250'
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
response = requests.get(url, headers=headers)
html_content = response.text
```
#### 解析网页结构
创建`BeautifulSoup`对象来解析下载下来的HTML字符串,提取所需的数据字段如电影名称、评分等。
```python
soup = BeautifulSoup(html_content, 'lxml')
movies = []
for item in soup.find_all('div', class_='item'):
title = item.select_one('.title').get_text(strip=True).split()[0]
rating_num = float(item.select_one('.rating_num').get_text())
movies.append({"Title": title, "Rating": rating_num})
```
#### 存储数据至CSV文件
借助内置模块csv将收集好的列表写入本地磁盘作为持久化存储[^3]。
```python
import csv
with open('douban_top_250.csv', mode='w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=["Title", "Rating"])
writer.writeheader()
writer.writerows(movies)
```
上述代码片段展示了如何通过Python脚本自动化地从豆瓣网获取热门影片及其对应的观众评价分数,并最终导出为易于阅读的表格形式以便后续分析处理。
阅读全文
相关推荐

















