python爬取数据保存到excel
时间: 2023-10-08 08:09:13 浏览: 139
1. 安装所需模块
使用Python爬虫需要安装requests、beautifulsoup4、openpyxl模块。可以通过以下命令进行安装:
```
pip install requests
pip install beautifulsoup4
pip install openpyxl
```
2. 爬取数据
以爬取豆瓣电影Top250为例,代码如下:
```python
import requests
from bs4 import BeautifulSoup
import openpyxl
# 定义表头
header = ['电影名称', '评分', '评价人数', '导演', '主演', '年份', '国家', '类型']
# 创建Excel工作簿
wb = openpyxl.Workbook()
ws = wb.active
ws.append(header)
# 爬取豆瓣电影Top250
url = 'https://movie.douban.com/top250'
for i in range(0, 250, 25):
params = {'start': i, 'filter': ''}
r = requests.get(url, params=params)
soup = BeautifulSoup(r.text, 'html.parser')
movies = soup.find_all('div', class_='info')
for movie in movies:
# 获取电影信息
name = movie.find('span', class_='title').text
rating_num = movie.find('span', class_='rating_num').text
rating_people = movie.find('div', class_='star').find_all('span')[-1].text[:-3]
director = movie.find('div', class_='bd').find_all('p')[0].text.split(':')[1].split('\n')[0].strip()
actors = movie.find('div', class_='bd').find_all('p')[0].text.split(':')[-1].strip()
year = movie.find('div', class_='bd').find_all('p')[1].text.split('/')[0].strip()
country = movie.find('div', class_='bd').find_all('p')[1].text.split('/')[1].strip()
genre = movie.find('div', class_='bd').find_all('p')[1].text.split('/')[-1].strip()
# 将电影信息写入Excel表格
row = [name, rating_num, rating_people, director, actors, year, country, genre]
ws.append(row)
# 保存Excel表格
wb.save('douban_movie_top250.xlsx')
```
3. 结果展示
运行上述代码后,会在当前目录下生成一个名为douban_movie_top250.xlsx的Excel文件,文件内容如下图所示:
![excel](https://img-blog.csdnimg.cn/20211029102914820.png)
阅读全文