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

Selenium爬取币安页面表格数据无法定位元素报错如何解决

问题原因分析
  • 固定硬等待不可靠:time.sleep(5) 无法适配不同网络环境下的动态页面加载速度,表格未完成渲染就执行定位逻辑就会触发元素不存在报错
  • 无头模式被反爬拦截:币安设置了反爬策略,默认无头模式的请求特征会被识别,返回的页面不含目标表格内容
  • 页面结构迭代:前端更新可能调整了目标元素的类名或嵌套结构,原XPath定位规则失效
  • Selenium版本兼容问题:新版本Selenium已废弃find_element_by_xpath系列方法,若你近期升级了依赖也会触发定位异常
修复后可用代码
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.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

options = Options()
options.add_argument("--headless=new")  # 采用新版无头模式,特征更接近普通浏览器
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")  # 模拟普通浏览器UA
options.add_argument("--disable-blink-features=AutomationControlled")  # 去除自动化标记,绕过反爬
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("useAutomationExtension", False)

driver = webdriver.Chrome(options=options)
# 移除webdriver特征,进一步规避反爬检测
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")

driver.get("https://www.binance.com/en/futures/funding-history/0")

# 显式等待最多20秒,直到表格tbody元素加载完成
wait = WebDriverWait(driver, 20)
table = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@class="rc-table-tbody"]')))

data = []
for tr in table.find_elements(By.XPATH, 'tr'):
    columns = tr.find_elements(By.XPATH, 'td')
    if len(columns) >=3:  # 跳过空行、异常行避免索引报错
        data.append({
            'Contract': columns[0].text,
            'Funding Rate': columns[2].text
        })

df = pd.DataFrame(data)
driver.quit()
补充注意事项
  • 若后续再出现定位失效,可手动打开目标页面按F12检查目标元素的类名、嵌套结构是否更新,同步修改XPath规则即可
  • 不要高频发起请求,避免被币安封禁IP

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:27:02