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

使用Selenium爬取stakingrewards表格报NoSuchElementException如何解决

问题原因排查
  • Chrome无头模式的默认UA会被网站反爬策略识别,返回的页面并非正常访问的内容,不存在table-wrap类元素
  • 隐式等待只能保证元素存在的最短等待时间,对于动态渲染的表格组件,需要用显式等待指定元素加载完成再定位
  • 你使用的find_element_by_class_name是Selenium 3的旧写法,Selenium 4+已经废弃该接口,可能引发兼容问题
修复后代码
from bs4 import BeautifulSoup
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

options = webdriver.ChromeOptions()
# 替换无头模式的默认UA,避免被反爬识别
options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36')
options.add_argument('headless')
options.add_argument("--enable-javascript")
options.add_argument('--no-sandbox')
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
# 去掉webdriver访问痕迹
options.add_argument("--disable-blink-features=AutomationControlled")

driver = webdriver.Chrome(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/')
# 显式等待最多20秒,直到table-wrap元素加载完成
try:
    element = WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.CLASS_NAME, "table-wrap"))
    )
    html = BeautifulSoup(driver.execute_script("return arguments[0].innerHTML;", element), 'html.parser')
    for item in html.findAll('div', {"class": "rt-tr-group"}):
        print(item.text.strip())
finally:
    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.03 12:06:04