使用爬虫爬取豆瓣电影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)
相关推荐
kisloy4 小时前
【爬虫入门第13讲】Scrapy 框架深度解析(四)核心配置与自定义扩展
网络·爬虫·scrapy
TlSfoward15 小时前
TLSFoward 能帮你看到什么 TLSFOWARD抓包工具
服务器·爬虫·网络协议·https
2501_9160074716 小时前
Python实现HTTPS爬虫的完整指南:使用requests、BeautifulSoup、Selenium和Scrapy
爬虫·python·ios·小程序·https·uni-app·iphone
'pi%'16 小时前
LangGraph 多智能体实战:搭建电力政策跟踪 Agent,实现网页爬虫、OCR 与 PDF 文档自动化解析
爬虫·pdf·ocr
杨先生哦16 小时前
【2026热端攻防系列 11/12】前端AI风控攻防实战:验证码缺陷、人机验证绕过、智能爬虫对抗与企业智能风控加固方案
前端·人工智能·笔记·爬虫·安全
久久学姐16 小时前
Python开发爬虫的常用技术架构
爬虫·python·http·框架·数据存储
tang7778917 小时前
分布式爬虫优化指南:如何用代理IP把采集效率提升300%
分布式·爬虫·python·tcp/ip·分布式爬虫·爬虫代理·代理ip
二十雨辰2 天前
[爬虫]-request
爬虫
狗都不学爬虫_2 天前
AI逆向 - 99aq中心滑块验证+登录(wasm纯算)
爬虫·python·网络爬虫
hyf3266333 天前
泛程序:从零开始搭建稳定程序项目框架
运维·服务器·爬虫·百度·seo