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

yahoo_fin的get_quote_table无返回表 如何稳定抓取雅虎财经成交量数据

问题解决方案

报错原因

ValueError: No tables found错误由雅虎财经反爬机制触发导致:短时间内高频请求会被雅虎服务器拦截,返回验证码页面或空白响应,而非正常的行情页面,因此pandas无法解析到对应表格。

现有yahoo_fin使用修复方案

  1. 增加异常捕获与重试机制,避免单次请求失败直接终止任务
  2. 加入请求间隔,降低请求频率,规避反爬触发阈值
  3. 在循环任务外层增加异常捕获,避免单次任务失败导致整个服务离线
    示例代码如下:
import yahoo_fin.stock_info as si
import time
from functools import wraps

# 重试装饰器,最多重试3次,每次间隔2秒
def retry(max_retries=3, delay=2):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for i in range(max_retries):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if i == max_retries - 1:
                        raise e
                    time.sleep(delay)
        return wrapper
    return decorator

@retry(max_retries=3, delay=2)
def fetchCurrentVolume(ticker):
    table = si.get_quote_table(ticker)
    currentVolume = table['Volume']
    # 每次成功请求后加1秒间隔,降低反爬触发概率
    time.sleep(1)
    return currentVolume

# 循环任务外层加异常捕获
from discord.ext import tasks
@tasks.loop(seconds=30) # 请求间隔建议不低于10秒
async def volume_monitor():
    try:
        vol = fetchCurrentVolume("AMZN")
        # 此处填写你的业务逻辑
    except Exception as e:
        # 仅打印错误不抛出,避免循环终止
        print(f"获取数据失败: {str(e)}")

替代方案

关于bs4提取动态数据的说明

bs4本身只能解析请求返回的静态HTML内容,如果成交量数据是页面加载后通过JavaScript异步请求渲染的,直接用requests获取页面源码后用bs4解析无法拿到对应数据,可选择以下两种更稳定的方案:

方案1:使用维护更完善的雅虎财经接口库

yfinance是目前社区维护更频繁的雅虎财经数据工具,稳定性高于yahoo_fin,使用示例:

import yfinance as yf
import time

def fetchCurrentVolume(ticker):
    stock = yf.Ticker(ticker)
    info = stock.info
    time.sleep(1)
    return info.get('volume', 0)

方案2:使用无头浏览器获取动态渲染数据

如果需要完全模拟浏览器行为绕过反爬,可以使用无头浏览器加载页面后直接提取你需要的xpath对应数据:

from playwright.sync_api import sync_playwright
import time

def fetchCurrentVolume(ticker):
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        page = browser.new_page()
        page.goto(f"https://finance.yahoo.com/quote/{ticker}")
        # 等待目标表格加载完成
        page.wait_for_selector('//div[@id="quote-summary"]/div/table/tbody/tr', timeout=10000)
        # 提取成交量对应行数据
        volume_row = page.locator('//div[@id="quote-summary"]/div/table/tbody/tr[contains(., "Volume")]')
        volume = volume_row.locator('td[2]').text_content()
        browser.close()
        time.sleep(2)
        return volume

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:06:02