You need to enable JavaScript to run this app. Python结合Beautiful Soup爬取IMDb:如何提取输出电影评分
优惠活动
大模型
产品
解决方案
定价
更多

Python结合Beautiful Soup爬取IMDb:如何提取输出电影评分

实现方案

  1. 调整遍历粒度:不要直接循环lister-item-header的h3标签,先定位每部电影对应的div.lister-item容器,片名、年份、评分所有字段都在这个容器内部。
  2. 评分定位:单条电影容器内,评分文本在span.ipl-rating-star__rating标签中,直接提取即可。
  3. 简化文本提取逻辑:弃用手动字符串替换的方式,用BS4原生get_text(strip=True)提取清洗后的文本,避免标签残留、属性变动导致的提取失效。

修正后可运行代码

import urllib.request
from bs4 import BeautifulSoup

# 替换为你的目标列表页地址
resp = urllib.request.urlopen('目标IMDb列表页地址')
soup = BeautifulSoup(resp.read(), 'lxml')

# 遍历所有电影条目
for item in soup.find_all('div', class_='lister-item'):
    # 提取片名、年份
    header = item.find('h3', class_='lister-item-header')
    film_name = header.find('a').get_text(strip=True)
    film_year = header.find('span', class_='lister-item-year text-muted unbold').get_text(strip=True)
    # 提取对应评分
    film_rating = item.find('span', class_='ipl-rating-star__rating').get_text(strip=True)
    # 按要求格式输出
    print(f"{film_name} {film_year} {film_rating}")

输出效果

运行后会逐行输出符合要求的格式内容:

Solaris (1972) 8.1
The Shawshank Redemption (1994) 9.3
The Godfather (1972) 9.2

内容的提问来源于stack exchange,提问作者Blogsky Project

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.11 11:06:04