用python爬取豆瓣电影top250
时间: 2023-10-24 18:08:25 浏览: 97
好的,下面是爬取豆瓣电影top250的python代码:
```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'}
movies = []
while url:
res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')
movie_list = soup.find('ol', class_='grid_view').find_all('li')
for movie in movie_list:
name = movie.find('span', class_='title').text
rating = movie.find('span', class_='rating_num').text
movies.append({'name': name, 'rating': rating})
next_page = soup.find('span', class_='next').find('a')
url = next_page['href'] if next_page else None
for movie in movies:
print(movie['name'], movie['rating'])
```
这段代码利用requests和BeautifulSoup库实现了对豆瓣电影top250的爬取,并输出了电影名称和评分。其中,我们使用了一个while循环来遍历每一页的电影信息,直到没有下一页为止。
阅读全文