爬虫豆瓣热门电影评分
时间: 2023-12-17 18:28:11 浏览: 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'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
movies = soup.find_all('div', class_='info')
for movie in movies:
title = movie.find('span', class_='title').get_text()
rating = movie.find('span', class_='rating_num').get_text()
print(title, rating)
```
这段代码使用requests库向豆瓣电影TOP250的网页发送请求,并使用BeautifulSoup库解析网页内容。然后,它找到每个电影的标题和评分,并将它们打印出来。
如果您想将这些数据保存到Excel中,可以使用Python的pandas库。以下是一个示例代码:
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
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_='info')
data = []
for movie in movies:
title = movie.find('span', class_='title').get_text()
rating = movie.find('span', class_='rating_num').get_text()
data.append([title, rating])
df = pd.DataFrame(data, columns=['Title', 'Rating'])
df.to_excel('top250.xlsx', index=False)
```
这段代码与前面的代码类似,但它将数据存储在一个列表中,然后使用pandas库将其转换为DataFrame对象。最后,它将DataFrame对象保存到Excel文件中。
阅读全文