使用爬虫爬取豆瓣电影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)
相关推荐
Buke..7 小时前
【小程序逆向】某游快爆 AI 逆向 sign参数:AI 辅助分析与 MCP 工具链实战
前端·人工智能·爬虫·python·小程序·notepad++
码农飞哥10 小时前
RAG 翻车实测 + LangGraph Agent 实时抓取修复
人工智能·爬虫·langchain·ai编程·亮数据
小白的成长路程12 小时前
移动版藏内容,AI爬虫直接跳过
人工智能·爬虫
IT毕设实战小研13 小时前
基于大数据的二手车数据分析与预测
java·大数据·后端·爬虫·python·算法·课程设计
深蓝电商API1 天前
AES 加密逆向思路
爬虫·aes 加密
Buke..2 天前
【APP 逆向】哔哩哔哩 sign 参数逆向(下):OLLVM 混淆还原 sign 算法
java·javascript·爬虫·python·算法
Buke..2 天前
【APP 逆向】哔哩哔哩 sign 参数逆向(上):Frida 反调试绕过与 unidbg 调用
java·开发语言·爬虫·python·安卓
归去来 兮2 天前
Python爬虫爬取数据案例
开发语言·爬虫·python
大鹏说大话3 天前
从爬虫到决策引擎:大数据下自媒体如何用Python挖掘用户痛点
开发语言·爬虫·python
Minner-Scrapy3 天前
Scrapy 2.17 源码解析:Scheduler 调度器与磁盘/内存双队列
java·爬虫·python·scrapy·网络爬虫·twisted