【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)
  • 结果展示
相关推荐
这是程序猿3 分钟前
基于java的ssm框架学生作业管理系统
java·开发语言·spring boot·spring·学生作业管理系统
XLYcmy20 分钟前
TarGuessIRefined密码生成器详细分析
开发语言·数据结构·python·网络安全·数据安全·源代码·口令安全
weixin_4334176729 分钟前
Canny边缘检测算法原理与实现
python·opencv·算法
梨落秋霜32 分钟前
Python入门篇【元组】
android·数据库·python
i小杨33 分钟前
python 项目相关
开发语言·python
zh_xuan33 分钟前
kotlin定义函数和变量
android·开发语言·kotlin
CoderCodingNo34 分钟前
【GESP】C++五级真题(贪心思想考点) luogu-P11960 [GESP202503 五级] 平均分配
开发语言·c++·算法
weixin_462446231 小时前
使用 Tornado + systemd 搭建图片静态服务(imgserver)
开发语言·python·tornado
源码获取_wx:Fegn08951 小时前
基于springboot + vue小区人脸识别门禁系统
java·开发语言·vue.js·spring boot·后端·spring
别多香了1 小时前
python基础之面向对象&异常捕获
开发语言·python