如何用Python爬取豆瓣电影250
时间: 2023-11-05 21:56:23 浏览: 81
你可以使用Python中的requests和beautifulsoup4库来爬取豆瓣电影250。
以下是爬取豆瓣电影250的代码示例:
```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):
params = {'start': str(i), 'filter': ''}
response = requests.get(url, params=params, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
movie_items = soup.find_all('div', class_='hd')
for movie in movie_items:
movie_name = movie.a.span.text.strip()
movie_list.append(movie_name)
print(movie_list)
```
这段代码会通过requests库向豆瓣电影250的网页发送请求,然后使用beautifulsoup4库解析网页内容并提取出电影名称。最后,将电影名称存储在一个列表中并打印出来。
阅读全文