爬取豆瓣top100的电影名,时间,演员名,并储存在Excel表格中Python代码
时间: 2024-03-31 11:38:26 浏览: 139
基于Python Scrapy实现的豆瓣电影数据采集爬虫系统 含数据库SQL和全部源代码
5星 · 资源好评率100%
好的,以下是Python代码:
```python
import requests
from bs4 import BeautifulSoup
import openpyxl
# 发送请求并获取网页内容
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')
# 创建Excel表格并添加表头
workbook = openpyxl.Workbook()
worksheet = workbook.active
worksheet.title = 'top100电影'
worksheet['A1'] = '电影名'
worksheet['B1'] = '时间'
worksheet['C1'] = '演员名'
# 获取电影名、时间、演员名,并添加到Excel表格中
for i in range(0, 100, 25):
url = f'https://movie.douban.com/top250?start={i}&filter='
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
movies = soup.find_all('div', class_='hd')
times = soup.find_all('div', class_='bd')
actors = soup.find_all('div', class_='bd')
for j in range(25):
movie_name = movies[j].a.span.text
time = times[j].p.text.split('\n')[1].strip().replace('\xa0/\xa0', '')
actor = actors[j].p.text.split('\n')[2].strip().replace('\xa0/\xa0', ', ')
worksheet.append([movie_name, time, actor])
# 保存Excel表格
workbook.save('top100电影.xlsx')
print('保存成功!')
```
这段代码会爬取豆瓣电影Top100的电影名、时间、演员名,并储存到一个名为 `top100电影.xlsx` 的Excel表格中。请注意,为了防止被反爬虫,我们在发送请求时加入了 `User-Agent` 头部信息。
阅读全文