用python爬取豆瓣电影前250名,并保存为excel格式,分析电影名称,明星,电影信息,电影简述,电影评论人数,上映国家,上映时间
时间: 2024-02-14 17:20:21 浏览: 22
好的,我已经明白了你的问题。答案如下:
首先,我们需要安装 requests,beautifulsoup4 和 xlwt 库,用于请求网页、解析 HTML 和保存到 Excel 文件。
```python
pip install requests beautifulsoup4 xlwt
```
接下来,我们需要先爬取豆瓣电影前250名的网页,然后分析网页结构并提取所需信息。代码如下:
```python
import requests
from bs4 import BeautifulSoup
import xlwt
# 请求网页
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')
movie_list = soup.find('ol', class_='grid_view').find_all('li')
# 提取所需信息
movies = []
for movie in movie_list:
# 电影名称
name = movie.find('span', class_='title').text
# 明星
stars = movie.find('div', class_='star').find_all('span')
star_str = ''
for star in stars:
star_str += star.text
# 电影信息
info = movie.find('div', class_='bd').find('p').text.strip()
# 电影简述
desc = movie.find('span', class_='inq').text if movie.find('span', class_='inq') else ''
# 电影评论人数
rating_num = movie.find('div', class_='star').find_all('span')[-1].text[:-3]
# 上映国家
country = info.split('/')[0].strip()
# 上映时间
year = info.split('/')[-2].strip()
movies.append([name, star_str, info, desc, rating_num, country, year])
```
最后,我们需要将提取到的信息保存到 Excel 文件中。代码如下:
```python
# 保存到 Excel 文件
book = xlwt.Workbook(encoding='utf-8', style_compression=0)
sheet = book.add_sheet('豆瓣电影Top250', cell_overwrite_ok=True)
sheet.write(0, 0, '电影名称')
sheet.write(0, 1, '明星')
sheet.write(0, 2, '电影信息')
sheet.write(0, 3, '电影简述')
sheet.write(0, 4, '电影评论人数')
sheet.write(0, 5, '上映国家')
sheet.write(0, 6, '上映时间')
for i in range(len(movies)):
movie = movies[i]
for j in range(len(movie)):
sheet.write(i+1, j, movie[j])
book.save('豆瓣电影Top250.xls')
```
这样就完成了豆瓣电影前250名的爬取和保存到 Excel 文件的操作。