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

Investing.com爬虫问题:非Selenium方案失效与Selenium提速需求

爬取Investing.com标普500期货涨跌幅的问题解决

是否只能使用Selenium?

不是。原方法失效大概率是网站启用了反爬策略(比如验证请求头、动态渲染数据),或者目标元素的class存在动态变化。不用Selenium也能实现爬取,具体方案见下文“能否不使用Selenium实现爬取”部分。

如何提升Selenium代码的响应速度?

  • 启用无头模式:使用Chrome新无头模式,避免加载浏览器UI,减少资源占用
    from selenium.webdriver.chrome.options import Options
    options = Options()
    options.add_argument('--headless=new')
    
  • 禁用非必要功能:关闭图片加载、GPU加速等,减少页面加载冗余耗时
    options.add_argument('--blink-settings=imagesEnabled=false')
    options.add_argument('--disable-gpu')
    options.add_argument('--disable-extensions')
    
  • 用显式等待替代固定休眠:精确等待目标元素出现后再操作,避免无意义的等待
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    
    wait = WebDriverWait(driver, 10)
    percent_elem = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'price_change-percent')))
    
  • 优化元素定位:如果目标class存在多个匹配项,先定位标普500期货的父容器,再在容器内查找目标元素,缩小定位范围
    # 先找到标普500期货的卡片容器(需根据实际页面结构调整XPath)
    container = wait.until(EC.presence_of_element_located((By.XPATH, '//div[contains(@class, "instrument-quote") and contains(text(), "S&P 500 Futures")]')))
    percent_elem = container.find_element(By.CLASS_NAME, 'price_change-percent')
    
  • 复用浏览器会话:如果需要多次爬取,不要每次都重新启动浏览器,复用已有会话可大幅减少启动耗时

能否不使用Selenium实现爬取?

可以,推荐两种高效方案:

方案1:直接调用网站API接口

Investing.com的大部分数据通过API动态加载,无需解析HTML:

  1. 打开浏览器开发者工具(F12),切换到「Network」标签,过滤「XHR/Fetch」
  2. 刷新标普500期货页面,查找包含期货数据的API请求(通常URL包含financialdata或futures关键词)
  3. 复制请求的URL、完整请求头(重点是User-Agent、Referer,部分场景需带上Cookie)
  4. 用httpx直接发送请求,解析JSON响应提取涨跌幅:
    import httpx
    
    headers = {
        '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',
        'Referer': 'https://www.investing.com/indices/us-spx-500-futures'
    }
    # 替换为实际找到的API URL
    api_url = 'https://api.investing.com/api/financialdata/xxx'
    response = httpx.get(api_url, headers=headers)
    data = response.json()
    # 根据实际JSON结构提取涨跌幅字段
    price_change_percent = data['priceChange']['percent']
    print(price_change_percent)
    

方案2:优化httpx+JS渲染工具

如果不想找API,可完善请求头模拟真实浏览器,同时用轻量工具处理动态渲染:
使用requests-html(基于Pyppeteer,比Selenium轻量)自动渲染页面JS:

from requests_html import HTMLSession

session = HTMLSession()
headers = {
    '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'
}
r = session.get('https://www.investing.com/indices/us-spx-500-futures', headers=headers)
r.html.render(timeout=10)  # 渲染JS生成的内容
span = r.html.find('.price_change-percent', first=True)
if span:
    print(span.text)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:34:59