使用BeautifulSoup无法获取Steam社区gameListRow类div的问题求助
解决Steam社区游戏页面动态内容爬取问题
问题原因
Steam个人游戏页面的游戏列表是JavaScript动态渲染的,requests库只能获取页面初始的静态HTML,里面并未包含gameListRow类的div元素,因此返回空列表。
解决方案
方案一:用Selenium模拟浏览器加载动态内容
通过模拟浏览器行为,等待页面JavaScript渲染完成后再获取源码,就能拿到包含游戏列表的完整HTML。
from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 初始化Chrome浏览器(需提前下载对应版本的chromedriver) driver = webdriver.Chrome() driver.get('https://steamcommunity.com/id/pintipanda/games/?tab=all') # 等待游戏列表元素加载,超时10秒 try: WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CLASS_NAME, 'gameListRow')) ) finally: html_text = driver.page_source driver.quit() soup = BeautifulSoup(html_text, 'lxml') divs = soup.find_all('div', {'class': 'gameListRow'}) game_ids = [div.get('id') for div in divs] print(game_ids)
注意:需先安装Selenium库(pip install selenium),并确保chromedriver版本与本地Chrome浏览器版本一致。
方案二:直接调用Steam的XML接口(更高效)
Steam页面加载游戏列表时会调用内部XML接口,直接请求该接口可获取结构化数据,无需处理动态渲染。
import requests from bs4 import BeautifulSoup # 请求XML格式的游戏列表数据 response = requests.get('https://steamcommunity.com/id/pintipanda/games/?tab=all&xml=1') soup = BeautifulSoup(response.text, 'xml') # 提取appID并构造对应id(原页面id格式为game_{appID}) games = soup.find_all('game') game_ids = [f"game_{game.find('appID').text}" for game in games] print(game_ids)
这种方法无需依赖浏览器驱动,请求速度更快,数据更稳定。
内容的提问来源于stack exchange,提问作者Vulp1s
相关产品推荐
相关产品推荐

