【python爬虫】—豆瓣电影Top250

豆瓣电影Top250

豆瓣榜单简介

  • 豆瓣电影 Top 250 榜单是豆瓣网站上列出的评分最高、受观众喜爱的电影作品。这个榜单包含了一系列优秀的影片,涵盖了各种类型、不同国家和时期的电影。

需求描述

  • 使用python爬取top250电影,获取相应电影排名,电影名,星级, 打分和评论人数信息,将信息输出到Excel表格中。

Python实现

  • 获取爬取网页
python 复制代码
def download_all_htmls(index = list(range(0, 250, 25))):
    htmls = []
    for idx in index:
        url = f"https://movie.douban.com/top250?start={idx}&filter="
        print("craw html:", url)

        # 豆瓣具有反爬虫机制,添加headers
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'}
        r = requests.get(url, headers = headers)
        
        if r.status_code != 200:
            raise Exception("error")
        htmls.append(r.text)
    return htmls
  • 解析得到单个网页内容
python 复制代码
def parse_single_heml(html):
    soup = BeautifulSoup(html, 'html.parser')
    article_items = soup.find('div', class_='article')\
            .find('ol', class_='grid_view')\
            .find_all('div', class_='item')
    
    datas = []
    for article_item in article_items:
        rank = article_item.find('div', class_='pic').find('em').get_text()
        info = article_item.find('div', class_='info')
        title = info.find('div', class_='hd').find('span', class_='title').get_text()
        stars = info.find('div', class_='bd').find('div', class_='star').find_all('span')

        rating_star = stars[0]["class"][0]
        rating_num = stars[1].get_text()
        comments = stars[3].get_text()

        datas.append({
            'rank': rank,
            'title': title,
            'rating_star': rating_star.replace("rating","").replace("-t",""),
            'rating_num': rating_num,
            'comments': comments.replace("人评价", "")
        })
    return datas
  • 爬取相关内容,并将结果写入Excel
python 复制代码
import requests
from bs4 import BeautifulSoup
import pandas as pd
import pprint
import json

htmls = download_all_htmls()
all_datas = []
for html in htmls:
    all_datas.extend(parse_single_heml(html))
df = pd.DataFrame(all_datas)
df.to_excel("practice03_豆瓣电影top250.xlsx", index=False)
  • 结果展示
相关推荐
Starry-sky(jing)3 分钟前
onnxruntime 安装后 GPU 没加速?3 条命令确认它跑在 CPU 还是 GPU
python·gpu·cuda·onnxruntime·推理加速
步行cgn4 分钟前
Spring AOP 实战:安全日志
python·安全·spring
北i7 分钟前
Dubbo 默认超时重试:把下游打雪崩的隐形放大器
开发语言·qt·dubbo
诺伦13 分钟前
OpenAI Agents API 公测拆解:托管编排+持久会话+自有沙箱搭一条自动增长流水线 | RiseClaw玄策
python·openai·ai agent·营销自动化·agent编排
10mAh18 分钟前
【Java】ArrayList 遍历删除为什么报错?三种写法与漏删复现
java·开发语言·windows
坊钰37 分钟前
【LangGraph框架入门级】2. 图核心概念:State、Node、Edge 与 Reducers
python·ai编程·langgraph
wewowilling39 分钟前
AI大模型开发--01Python基础(无废话)
开发语言·python·函数
小猴子爱上树40 分钟前
跨境电商AI图片翻译工具:批量图片翻译、视频字幕翻译与智能抠图一站式解决
大数据·人工智能·python·音视频
5G微创业43 分钟前
去除抖音视频水印的Python实现
python·微信小程序·去水印
WeiXin_DZbishe1 小时前
基于微信小程序的本地闲置物品交易平台-计算机毕设 附源码【课程设计】26825
vue.js·spring boot·python·微信小程序·架构·php·课程设计