【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)
  • 结果展示
相关推荐
好家伙VCC35 分钟前
**神经编码新视角:用Python实现生物启发的神经信号压缩与解码算法**在人工智能飞速发展的今天
java·人工智能·python·算法
踏着七彩祥云的小丑7 小时前
pytest——Mark标记
开发语言·python·pytest
Dream of maid7 小时前
Python12(网络编程)
开发语言·网络·php
W23035765738 小时前
经典算法:最长上升子序列(LIS)深度解析 C++ 实现
开发语言·c++·算法
Y4090018 小时前
【多线程】线程安全(1)
java·开发语言·jvm
不爱吃炸鸡柳8 小时前
Python入门第一课:零基础认识Python + 环境搭建 + 基础语法精讲
开发语言·python
minji...9 小时前
Linux 线程同步与互斥(三) 生产者消费者模型,基于阻塞队列的生产者消费者模型的代码实现
linux·运维·服务器·开发语言·网络·c++·算法
Dxy12393102169 小时前
Python基于BERT的上下文纠错详解
开发语言·python·bert
SiYuanFeng10 小时前
Colab复现 NanoChat:从 Tokenizer(CPU)、Base Train(CPU) 到 SFT(GPU) 的完整踩坑实录
python·colab