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

Python使用Selenium获取stakingrewards网站表格Xpath失败问题求解

问题原因

  • 反爬识别:目标站点有成熟的反爬策略,默认配置的Chrome无头模式会被直接识别,返回拦截页面而非正常内容,自然无法定位到表格元素
  • 定位逻辑错误:你代码中变量命名为iframes但实际定位的是//html/body/路径,和查找表格、查找iframe的需求完全无关,定位逻辑本身存在错误
  • 无头模式参数不完善:旧版Chrome无头模式的指纹特征非常明显,缺少反识别参数很容易被拦截
  • 等待策略不合理:隐式等待只能应对常规元素加载延迟,无法校验反爬返回的异常页面

修复后可运行代码

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service

options = webdriver.ChromeOptions()
# 核心反爬参数
options.add_argument('--headless=new') # 使用Chrome新版无头模式,指纹更接近正常浏览器
options.add_argument('--no-sandbox')
options.add_argument("window-size=1200x600")
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
# 覆盖webdriver指纹
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
})

driver.get('https://www.stakingrewards.com/cryptoassets')

try:
    # 显式等待表格加载,最多等15秒,匹配目标站表格类名
    table = WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.XPATH, '//table[contains(@class, "rt-table")]'))
    )
    # 打印表格内容验证
    print(table.get_attribute("outerHTML"))
except Exception as e:
    print("元素加载超时,可通过截图验证当前页面状态:", str(e))
    driver.save_screenshot("current_page.png")

driver.quit()

额外注意事项

  • 如果仍然被拦截,可以暂时关闭无头模式,观察打开的页面是否有人机校验步骤,若有可添加验证码识别逻辑或者拉长请求间隔
  • 该网站表格为懒加载,要获取全量数据需要模拟滚动操作,逐次加载更多行数据
  • 不要高频发起请求,避免IP被临时封禁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:42:01