利用requests库和BeautifulSoup库爬取豆瓣电影top25的名字和评分并写入列表中
时间: 2024-04-01 18:34:55 浏览: 14
好的,以下是使用 Python 的 requests 和 BeautifulSoup 库爬取豆瓣电影 top250 的电影名称和评分,并将结果写入列表中的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 请求 URL 和 headers
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'}
# 发送请求
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
# 解析页面
movies = soup.find_all('div', class_='hd')
ratings = soup.find_all('span', class_='rating_num')
results = []
for i in range(len(movies)):
movie = movies[i].a.span.text
rating = ratings[i].text
results.append([movie, rating])
print(results)
```
以上代码会输出豆瓣电影 top250 的电影名称和评分,并将结果写入列表中。输出的格式为:
```
[['肖申克的救赎', '9.7'], ['霸王别姬', '9.6'], ['这个杀手不太冷', '9.6'], ...]
```
您可以根据需求进行修改和扩展。