You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的Selenium获取Steam全部畅销游戏标题?

解决方法:获取Steam畅销页所有游戏标题(基于Selenium)

你的代码只返回首个标题,是因为find_element_by_xpath只会匹配页面中第一个符合条件的元素。要获取所有游戏标题,只需做以下关键修改:

核心改动说明

  • 使用复数形式的find_elements_by_xpath(注意末尾的s),它会返回页面中所有匹配的元素列表
  • 添加显式等待,确保页面加载完成后再获取元素,避免因网络延迟导致的内容缺失

修改后的完整代码

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd

options = Options()
options.binary_location = r"{binary_location}"
driver = webdriver.Firefox(executable_path=r"{driver_location}", options=options)

driver.get("https://store.steampowered.com/search/?filter=topsellers")

# 显式等待10秒,直到所有标题元素加载完成
wait = WebDriverWait(driver, 10)
title_elements = wait.until(EC.presence_of_all_elements_located((By.XPATH, "//span[@class='title']")))

# 遍历元素列表,提取所有标题文本
titles = [elem.text for elem in title_elements]

# 打印所有标题
for idx, title in enumerate(titles, 1):
    print(f"{idx}. {title}")

# 可选:将标题存入DataFrame用于数据集制作
game_df = pd.DataFrame({"游戏标题": titles})
print("\n生成的数据集预览:")
print(game_df.head())

driver.quit()

代码解释

  1. 显式等待:通过WebDriverWait和presence_of_all_elements_located确保页面上所有标题元素都已加载,避免出现空列表的情况
  2. 元素列表遍历:用列表推导式遍历所有匹配的标题元素,提取每个元素的text属性,得到完整的标题列表
  3. 数据集整合:可以直接将标题列表转为Pandas DataFrame,方便后续数据集的处理和保存

内容的提问来源于stack exchange,提问作者Vishal Padia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 20:55:24