【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)
  • 结果展示
相关推荐
沐知全栈开发21 小时前
滑块(Slider)在网页设计中的应用与优化
开发语言
Love Song残响21 小时前
揭秘Libvio爬虫:动态接口与逆向实战
爬虫
乔江seven21 小时前
【Flask 进阶】3 从同步到异步:基于 Redis 任务队列解决 API 高并发与长耗时任务阻塞
redis·python·flask
又见野草21 小时前
C++类和对象(下)
开发语言·c++
rit843249921 小时前
基于MATLAB的环境障碍模型构建与蚁群算法路径规划实现
开发语言·算法·matlab
pchaoda21 小时前
基本面因子计算入门
python·matplotlib·量化
lang2015092821 小时前
Java JSR 250核心注解全解析
java·开发语言
Wpa.wk21 小时前
接口自动化测试 - 请求构造和响应断言 -Rest-assure
开发语言·python·测试工具·接口自动化
czhc114007566321 小时前
协议 25
java·开发语言·算法
岱宗夫up21 小时前
机器学习:标准化流模型(NF)
人工智能·python·机器学习·生成对抗网络