python爬取豆瓣电影top250的代码
时间: 2023-07-23 13:53:35 浏览: 99
好的,以下是Python爬取豆瓣电影Top250的代码:
```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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
movie_list = []
for i in range(0, 250, 25):
r = requests.get(url + '?start=' + str(i), headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
movies = soup.find_all('div', {'class': 'info'})
for movie in movies:
title = movie.find('span', {'class': 'title'}).text
rating = movie.find('span', {'class': 'rating_num'}).text
movie_list.append({'title': title, 'rating': rating})
for movie in movie_list:
print(movie['title'], movie['rating'])
```
这个代码使用requests和beautifulsoup4库来爬取豆瓣电影Top250的网页,并且输出每个电影的标题和评分。我们通过循环每页数据,找到包含电影信息的HTML标签,然后从中提取电影标题和评分,最后打印输出。
阅读全文