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

Selenium抓取内容与浏览器不一致,无法找到Dune查询结果表

解决方法

问题核心是页面标签页为动态切换模式,默认加载的是第一个标签(如查询定义),你需要的「Query Results」是第二个标签,必须主动切换后才能抓取到对应内容。此外固定sleep可靠性差,建议用显式等待确保元素完全加载。

修改后的代码

import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.102 Safari/537.36"
url="https://dune.com/queries/604672/1128634"
chromedriver_path = "E:\\py\\testsoup\\win\\chromedriver.exe"

service = Service(chromedriver_path)
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--incognito')
options.add_argument('--headless')
options.add_argument(f'user-agent={USER_AGENT}')
options.add_argument('--window-size=1920,1080')  # 解决headless模式下页面布局异常问题

driver = webdriver.Chrome(service=service, options=options)
driver.get(url)

try:
    # 等待并切换到「Query Results」标签页
    result_tab = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, "//div[contains(text(), 'Query Results')]"))
    )
    result_tab.click()

    # 等待目标表格加载完成
    WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.CLASS_NAME, "table_table__fuS_N"))
    )

    # 解析页面并提取表格
    soup = BeautifulSoup(driver.page_source, 'html.parser')
    table_html = soup.find("table", {"class": "table_table__fuS_N"})
    
    # 转换为DataFrame(可选)
    df = pd.read_html(str(table_html))[0]
    print(df)
    
finally:
    driver.quit()

# 保存页面源码(可选)
with open(".\\url.html", "w", errors="ignore") as f:
    f.write(soup.prettify())

关键调整说明

  • 主动切换标签页:通过显式等待找到「Query Results」标签并点击,确保切换到目标内容区域。
  • 替换固定等待:用WebDriverWait替代sleep,只有当目标元素出现后才继续执行,避免因加载慢导致的抓取失败。
  • 优化headless模式:添加窗口大小参数,避免无界面模式下页面渲染异常;同时显式设置UA,匹配真实浏览器环境。
  • 异常安全处理:用try-finally确保浏览器无论是否报错都能正常关闭。

如果文本定位标签失败,可改用aria属性定位,替换标签定位的代码:

result_tab = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, "//button[@aria-controls='tabs--2-']"))
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:15:35