如何用Python爬取Steam页面全部游戏数据 仅返回单条结果如何解决
问题原因分析
- HTML规范中id属性是全局唯一的,原代码中
find_all('div', id='NewReleasesRows')只会返回1个包含所有游戏的容器元素,而非逐个的游戏条目,遍历这个容器对象自然只能拿到第一个游戏的信息。 - 原代码中查找游戏容器的语法错误:
soup.find('div', 'class', class_='tab_content_ctn sub')多传了冗余的位置参数'class',属于BeautifulSoup用法错误。 - 代码中使用的请求头变量
h没有定义,直接运行会报错,且缺失合理UA的请求容易被Steam反爬拦截,返回异常的页面内容。
修正后可运行代码
import requests from bs4 import BeautifulSoup # 定义请求头,避免被反爬拦截 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', 'Accept-Language': 'zh-CN,zh;q=0.9' } url = 'https://store.steampowered.com/category/sports_and_racing/#p=0&tab=NewReleases' r = requests.get(url, headers=headers) r.encoding = 'utf-8' soup = BeautifulSoup(r.text, 'html.parser') # 直接获取游戏列表容器 games_container = soup.find('div', id='NewReleasesRows') # 查找容器下所有游戏条目 all_games = games_container.find_all('a', class_='tab_item') for each in all_games: title = each.find('div', class_='tab_item_name').text print(f'title:{title}')
改动说明
- 补充了合法的请求头,解决反爬拦截和变量未定义的问题。
- 先定位到游戏列表的容器
NewReleasesRows,再查找容器下所有class为tab_item的游戏条目,遍历每个条目获取标题。 - 修正了BeautifulSoup查找元素的冗余参数问题。
- 如果需要获取多页数据,修改URL中
p=0的页码参数循环请求即可。
内容的提问来源于stack exchange,提问作者luka nadiradze
相关产品推荐
相关产品推荐

