使用爬虫爬取豆瓣电影Top250(方法一)

简介:主要使用bs4、request、pandas等模块,实现数据的爬取和存储。

目前存在一点小问题,就是个别电影的导演、演员、上映年份和地区等信息与大部分电影的这些信息的格式有细微差别,导致正则表达式无法正常匹配到个别电影的信息,出现复用前一部电影的信息的情况。

python 复制代码
from bs4 import BeautifulSoup
import requests, time, re
from random import randint
import pandas as pd

url_list = ['https://movie.douban.com/top250']
base_url = 'https://movie.douban.com/top250?start={start}'
for start in range(25, 251, 25):
    url_list.append(base_url.format(start=start))

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0'}
movie_info = []
details = []

for url in url_list:
    time.sleep(randint(1, 3))
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')
    movie_items = soup.find_all('div', class_='item')
    for movie in movie_items:
        # 获取排名
        rank = movie.find('em').text.strip()
        # 获取电影标题
        title = movie.find('span', class_='title').text.strip()
        # 获取电影导演、演员、年份、上映地区等信息
        info = movie.find('div', class_='bd').find('p').text.strip()
        # 由于info这条数据包含了很多信息,需要使用正则拆分开
        #print(info)
        pattern = re.compile(r"导演: (.*?)\s+主演: (.*?)\s+(\d{4})\s+/\s+(.*?)\s+/\s+(.*)")
        match = re.search(pattern, info)
        if match:
            director = match.group(1).strip()
            actors = match.group(2).strip()
            year = match.group(3).strip()
            countries = match.group(4).strip().split(' ')
            genres = match.group(5).strip().split(' ')

        # 获取评分信息
        rating_num = movie.find('span', class_='rating_num').text.strip()
        # 获取评价人数信息
        rate_people_num = movie.find('div', class_='star').find_all('span')[3].text.strip()
        # 将信息进行汇总
        mock_data = {'排名': rank, '电影名称': title, '导演': director, '演员': actors, '上映年份': year, '上映地区': countries, '电影类型': genres,'评分': rating_num,
                     '投票人数': rate_people_num}
        print(mock_data)
        movie_info.append(mock_data)

df = pd.DataFrame(movie_info,columns=['排名', '电影名称', '导演', '演员', '上映年份', '上映地区', '电影类型', '评分', '投票人数'])
excel_path = 'movie_info.xlsx'
df.to_excel(excel_path, index=False)
相关推荐
tang777898 小时前
小红书平台用什么代理 IP 比较好?2026年3月实测数据 + 选型推荐
网络·爬虫·python·网络协议·tcp/ip·数据挖掘·ip
进击的雷神12 小时前
突破POST分页与IP封锁:基于表单提交和代理转发的新闻爬虫设计
爬虫·网络协议·tcp/ip
小邓睡不饱耶18 小时前
东方财富股吧话题爬虫实现:从接口请求到Excel数据落地
爬虫·excel
进击的雷神19 小时前
攻克动态列表页结构:基于ID与URL双字段协同提取的精准爬虫设计
爬虫·spiderflow
进击的雷神2 天前
分页参数推导、嵌套数据提取、多语言地址判断、去重插入检查——韩国Koplas展爬虫四大技术难关攻克纪实
爬虫·python
xxjj998a2 天前
Python 爬虫实战案例 - 获取社交平台事件热度并进行影响分析
开发语言·爬虫·python
三三有猫2 天前
爬虫代理基础知识:为什么用与怎么用
开发语言·c++·爬虫
白日与明月2 天前
Pandas 读取文本数据 (Text I/O) 速查表
爬虫·python·pandas
逆向新手2 天前
chrome-devtools-mcp不能远程调试的问题与解决方法_2026-03-25
爬虫·ai编程·逆向
ZTLJQ2 天前
数据采集的工业级武器:Python爬虫框架完全解析
开发语言·爬虫·python