Python结合Beautiful Soup爬取IMDb:如何提取输出电影评分
实现方案
- 调整遍历粒度:不要直接循环
lister-item-header的h3标签,先定位每部电影对应的div.lister-item容器,片名、年份、评分所有字段都在这个容器内部。 - 评分定位:单条电影容器内,评分文本在
span.ipl-rating-star__rating标签中,直接提取即可。 - 简化文本提取逻辑:弃用手动字符串替换的方式,用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
相关产品推荐
相关产品推荐

