使用爬虫爬取豆瓣电影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)
相关推荐
吴秋霖2 天前
主流反爬虫、反作弊防护与风控对抗手段
爬虫·算法·反爬虫技术
hui函数2 天前
scrapy框架-day02
后端·爬虫·python·scrapy
用户051610461673 天前
爬虫 API 技术全解析:从原理到实战的高效数据采集指南
爬虫·api
xiaoxiongip6664 天前
动态ip适合挂什么项目
网络·爬虫·python·网络协议·tcp/ip·ip
q567315235 天前
自动化拨号爬虫体系:虚拟机集群部署与增量管理
运维·爬虫·网络协议·自动化
电商API_180079052475 天前
淘宝商品视频批量自动化获取的常见渠道分享
java·爬虫·自动化·网络爬虫·音视频
果壳~6 天前
【Python】爬虫html提取内容基础,bs4
爬虫·python·html
jay神6 天前
基于Python的商品爬取与可视化系统
爬虫·python·数据分析·毕业设计·可视化系统
华科云商xiao徐6 天前
如何在C语言环境中借助Linux库构建高效网络爬虫
爬虫·数据挖掘·数据分析
明远湖之鱼6 天前
巧用 Puppeteer + Cheerio:批量生成高质量 Emoji 图片
前端·爬虫·node.js