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

从Yahoo Finance批量提取股指周度历史数据至Excel的VBA方案咨询

用Excel VBA从Yahoo Finance批量提取股指周度历史数据(适配Chrome)

环境准备

因为IE已停用,改用Selenium Basic驱动Chrome实现动态网页数据抓取,这是适配现代浏览器的可靠方案:

  • 安装Selenium Basic工具包,完成后自动注册相关组件
  • 下载与你的Chrome浏览器版本匹配的ChromeDriver,解压后放到Selenium安装目录或系统PATH路径下
  • 打开Excel VBA编辑器,通过「工具→引用」勾选「Selenium Type Library」

批量抓取的VBA宏代码

以下代码支持同时处理多只股指/基金,自动抓取周度历史数据并写入Excel:

Sub 批量抓取Yahoo股指周度数据()
    Dim driver As New ChromeDriver
    Dim ws As Worksheet
    Dim tickerList As Variant
    Dim i As Integer, rowNum As Integer
    Dim table As WebElement, rows As WebElements, cols As WebElements
    
    ' 自定义要抓取的股指/基金代码列表
    tickerList = Array("INDEX", "VOO")
    
    ' 启动Chrome浏览器
    driver.Start "chrome"
    driver.Window.Maximize
    
    ' 遍历每一个目标代码
    For i = LBound(tickerList) To UBound(tickerList)
        ' 新建工作表存储当前代码数据
        Set ws = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
        ws.Name = tickerList(i)
        
        ' 打开对应历史数据页面
        driver.Get "https://finance.yahoo.com/quote/" & tickerList(i) & "/history?p=" & tickerList(i)
        
        ' 等待页面加载
        driver.Wait 2000
        
        ' 切换到周度数据视图
        driver.FindElementById("dropdown-menu").Click
        driver.FindElementByXPath("//span[text()='Weekly']").Click
        driver.Wait 3000 ' 等待数据刷新
        
        ' 定位历史数据表格
        Set table = driver.FindElementByXPath("//table[@data-test='historical-prices']")
        Set rows = table.FindElementsByTag("tr")
        
        ' 写入表头
        rowNum = 1
        Set cols = rows(0).FindElementsByTag("th")
        For Each col In cols
            ws.Cells(rowNum, col.Index).Value = col.Text
        Next col
        rowNum = rowNum + 1
        
        ' 逐行写入数据
        For Each row In rows
            If row.Index > 0 Then ' 跳过表头行
                Set cols = row.FindElementsByTag("td")
                For Each col In cols
                    ws.Cells(rowNum, col.Index).Value = col.Text
                Next col
                rowNum = rowNum + 1
            End If
        Next row
        
        ' 自动调整列宽
        ws.UsedRange.Columns.AutoFit
    Next i
    
    ' 关闭浏览器
    driver.Quit
    Set driver = Nothing
    MsgBox "数据抓取完成!"
End Sub

关键说明

  • 扩展抓取范围:直接在tickerList数组中添加股指代码即可,比如"SPY"、"NASDAQ"等
  • 等待时间调整:根据网络速度修改Wait的毫秒数,确保页面数据完全加载
  • 元素定位适配:若Yahoo Finance页面结构更新,需通过Chrome开发者工具(F12)重新获取元素的XPath或ID

注意事项

  • 避免短时间内频繁请求,防止触发反爬机制,可适当延长等待间隔
  • 确保ChromeDriver版本与Chrome浏览器版本完全匹配,否则会出现启动失败的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 13:42:36