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

使用Python+Selenium爬取Vanguard延时加载基金数据失败如何解决?

调整方案

核心问题原因

你遇到的问题由两个原因导致:

  • Vanguard站点会识别默认的Chrome无头浏览器特征,拦截页面数据加载
  • 你使用的元素定位器语法错误,等待逻辑没有触发,数据还没渲染就提前抓取了页面源码

具体修改点

  1. 补充Chrome启动参数,绕过无头浏览器识别
  2. 修正元素等待规则,等待基金表格的行元素渲染完成后再提取数据
  3. 新增超时异常捕获,避免加载失败时程序直接崩溃

修改后完整代码

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
import os

dirname = os.path.dirname(__file__)
options = webdriver.ChromeOptions()
# 替换旧无头模式为新无头模式,避免被识别
options.add_argument('--headless=new')
# 模拟普通浏览器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')
# 禁用沙箱与GPU,减少无头模式兼容性问题
options.add_argument('--no-sandbox')
options.add_argument('--disable-gpu')
options.add_argument('--disable-dev-shm-usage')

browser = webdriver.Chrome(options=options, executable_path=os.path.join(dirname, 'chromedriver'))
symbol = 'vbirx'
url_vanguard = 'https://investor.vanguard.com/mutual-funds/profile/overview/{}'
browser.get(url_vanguard.format(symbol))

try:
    # 等待基金表格的行元素加载完成,最多等待15秒
    WebDriverWait(browser, 15).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, 'table[role="presentation"] tbody tr'))
    )
except TimeoutException:
    print("页面加载超时,请检查网络或调整等待时长")
    browser.quit()
    exit()

html = browser.page_source
mySoup = BeautifulSoup(html, 'html.parser')
htmlData = mySoup.find('table',{'role':'presentation'})
table = htmlData.find('tbody')
print('table: \n',table)

browser.quit()

补充说明

不需要等待data-delayed-src属性的iframe消失,该iframe是广告统计用的,和基金数据加载没有关联。如果需要提取其他没有ID的元素,都可以用CSS属性选择器[属性名="属性值"]的方式定位,和ID定位的效果一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:15:04