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

Selenium爬取Oculus Quest游戏时XPath定位无法获取a标签href问题

问题根源

你编写的XPath最终匹配到的是存储游戏标题的div节点,并非需要的a标签。div元素本身不存在href属性,因此无法获取到对应链接。

解决方案

调整XPath定位逻辑即可,两种常用实现方式:

  • 方式1:反向定位,先匹配目标标题div,再查找它前面的同级a标签
from selenium.webdriver.common.by import By

game_title = "The Last Clockwinder"
submit = driver.find_element(
    by=By.XPATH,
    value="//div[@class='store-section-item__meta-name' and contains(text(), '{}')]/preceding-sibling::a[@class='store-section-item-tile']".format(game_title)
)
print(submit.get_attribute("href"))
  • 方式2:通过共同父容器定位(推荐,容错性更高)
    游戏封面a标签和标题div同属一个商品卡片父容器,先定位到包含目标标题的父容器,再在容器内查找a标签,避免同级节点顺序变动导致定位失败:
submit = driver.find_element(
    by=By.XPATH,
    value="//div[contains(@class, 'store-section-item') and .//div[contains(@class, 'store-section-item__meta-name') and contains(text(), '{}')]]/a[contains(@class, 'store-section-item-tile')]".format(game_title)
)
print(submit.get_attribute("href"))
注意事项
  • 如果页面元素类名存在动态拼接的随机后缀,不要使用@class='xxx'的精确匹配,替换为contains(@class, 'xxx')的模糊匹配即可
  • 上述代码获取到的是相对路径,若需要可直接访问的完整链接,拼接域名前缀https://www.oculus.com即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 21:48:14