34行代码实现豆瓣电影TOP250数据爬取与存储
import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:124.0) Gecko/20100101 Firefox/124.0'} # 设置请求头
df = pd.DataFrame(columns=["排名", "标题", "链接", "导演", "演员", "评分", "年份", "发行地", "类型", "评价人数", "简介"])# 创建空DataFrame
urls = ['https://movie.douban.com/top250?start={}&filter='.format(i * 25) for i in range(10)]# 生成页面地址列表
for url in urls:
time.sleep(1) # 暂停1秒,以避免请求过于频繁
session = requests.Session() # 创建一个Session对象
res = session.get(url, headers=HEADERS) # 使用Session保持会话
soup = BeautifulSoup(res.text, "html.parser") # 使用BeautifulSoup解析页面内容
movie_items = soup.find_all("div", class_="item") # 找到所有包含电影信息的<div>标签
for item in movie_items:
rank = item.find("em").text # 提取电影排名
title = item.find("span", class_="title").text # 提取电影标题
score = item.find("span", class_="rating_num").text # 提取评分
link = item.find("a").get("href") # 提取电影链接
info = item.find("div", class_="bd").find("p").text.strip().split("\n") # 提取其他信息并进行处理
people_info = info[0].strip().split("\xa0\xa0\xa0") #人员信息
other_info = info[1].strip().split("\xa0/\xa0") #其他信息
director = people_info[0].replace("导演: ", "").strip() #导演
actor = people_info[1].replace("主演: ", "").strip() if len(people_info) > 1 else "" #主演信息
year = other_info[0].strip() #年份
country = other_info[1].strip() #发行地
genre = other_info[2].strip() #类型
number_of_reviews = item.find("div", class_="star").find_all("span")[-1].text #评论人数
quote = item.find("span", class_="inq").text if item.find("span", class_="inq") else "" #简介
df = df.append({"排名": rank, "标题": title, "链接": link, "导演": director, "演员": actor, "评分": score,"年份": year, "发行地": country, "类型": genre, "评价人数": number_of_reviews, "简介": quote},ignore_index=True) # 将提取的信息添加到DataFrame中
print(rank, title, link, director, actor, score, year, country, genre, number_of_reviews, quote)
print("爬完了")
df.to_excel("豆瓣电影top250.xlsx", sheet_name="豆瓣电影top250数据", na_rep="")# 保存数据到Excel文件