豆瓣网站爬取top250电影信息
时间: 2025-07-21 21:46:51 浏览: 6
### 豆瓣电影Top250数据爬取方法
为了实现豆瓣电影Top250的信息抓取,可以采用Python中的`requests`库来发送HTTP请求并获取网页内容,再利用`BeautifulSoup`或`lxml`解析HTML文档结构,提取所需字段。具体操作如下所示:
#### 发送请求与接收响应
通过构建URL模板以及循环遍历每一页链接地址,模拟浏览器行为向服务器发起GET请求。
```python
import requests
from lxml import etree
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
}
url_template = "https://movie.douban.com/top250?start={}"
for i in range(0, 250, 25):
url = url_template.format(i)
response = requests.get(url=url, headers=headers)
```
#### 解析页面内容
使用XPath表达式定位目标节点位置,进而读取出各部影片的相关属性值。
```python
html = etree.HTML(response.text)
film_names = html.xpath('//div[@class="item"]//span[@class="title"][1]/text()')
directors_and_actors = []
ratings = html.xpath('//div[@class="star"]/span[2]/text()')
votes = html.xpath('//div[@class="star"]/span[4]/text()')
for item in html.xpath('//p[@class=""]'):
directors_and_actors.append(item.xpath('string(.)').strip())
```
#### 数据存储
最后一步就是把收集好的资料按照一定格式写入文件当中去,这里选用CSV作为输出形式之一。
```python
import csv
with open('douban_top250.csv', mode='w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['Film Name', 'Director & Actor', 'Rating', 'Vote'])
for index in range(len(film_names)):
row_data = [
film_names[index],
directors_and_actors[index],
ratings[index].replace(" ", "").replace("\n", ""),
votes[index].split()[1][:-3]
]
writer.writerow(row_data)
```
上述过程展示了完整的爬虫流程[^1]。
阅读全文
相关推荐

















