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

求助:使用VBA提取巴西央行网页指定表格数据失败

解决VBA提取巴西央行官网动态数据的问题

问题根源

巴西央行官网采用Angular框架构建,页面内容为动态渲染生成。你之前使用的XMLHTTP60仅能获取初始静态HTML源码,无法加载JavaScript渲染后的DOM元素,因此无法定位到目标节点。


方案一:使用Selenium Basic(推荐)

Selenium可模拟真实浏览器完整加载页面,获取渲染后的DOM结构,是处理动态网站的可靠方案。

前置准备

  1. 安装Selenium Basic
  2. 在VBA编辑器中引用Selenium Type Library(工具→引用)
  3. 下载对应浏览器的驱动(如ChromeDriver),确保版本与浏览器匹配,并放入系统PATH目录或Excel宏文件所在目录

示例代码

Sub GetBCBExchangeRate()
    Dim driver As New ChromeDriver
    Dim targetElement As WebElement
    
    ' 启动浏览器并访问目标网站
    driver.Start "chrome"
    driver.Get "https://www.bcb.gov.br/"
    
    ' 等待动态内容渲染完成(可根据网络情况调整等待时间)
    driver.Wait 5000
    ' 精准等待目标元素加载:
    ' driver.WaitUntil ElementIsPresent, By.CssSelector, "#home > div > div:nth-child(1) > div.componente.cotacao > div > cotacao > table:nth-child(1) > tbody > tr:nth-child(1) > td:nth-child(2) > span"
    
    ' 用CSS选择器定位目标元素并提取数值
    Set targetElement = driver.FindElementByCss("#home > div > div:nth-child(1) > div.componente.cotacao > div > cotacao > table:nth-child(1) > tbody > tr:nth-child(1) > td:nth-child(2) > span")
    ' 或使用XPath定位:
    ' Set targetElement = driver.FindElementByXPath("/html/body/app-root/app-root/div/div/main/dynamic-comp/div/div/div/div[1]/div[1]/div/cotacao/table[1]/tbody/tr[1]/td[2]/span")
    
    ' 将结果写入单元格
    Range("A1").Value = targetElement.Text
    
    ' 关闭浏览器
    driver.Quit
    Set driver = Nothing
End Sub

方案二:使用InternetExplorer对象(兼容备选)

若无法安装Selenium,可尝试IE控件(注意:部分现代网站对IE兼容性较差,可能失效)

示例代码

Sub GetBCBData_IE()
    Dim ie As Object
    Dim targetElement As Object
    
    Set ie = CreateObject("InternetExplorer.Application")
    ie.Visible = True ' 设置为False可后台运行
    ie.Navigate "https://www.bcb.gov.br/"
    
    ' 等待页面加载完成
    Do While ie.Busy Or ie.ReadyState <> 4
        DoEvents
    Loop
    ' 额外等待动态内容渲染
    Application.Wait Now + TimeValue("00:00:05")
    
    ' 尝试用CSS选择器定位
    On Error Resume Next
    Set targetElement = ie.Document.querySelector("#home > div > div:nth-child(1) > div.componente.cotacao > div > cotacao > table:nth-child(1) > tbody > tr:nth-child(1) > td:nth-child(2) > span")
    On Error GoTo 0
    
    If Not targetElement Is Nothing Then
        Range("A1").Value = targetElement.innerText
    Else
        ' 备选:用XPath定位
        Set targetElement = ie.Document.evaluate("/html/body/app-root/app-root/div/div/main/dynamic-comp/div/div/div/div[1]/div[1]/div/cotacao/table[1]/tbody/tr[1]/td[2]/span", ie.Document, Nothing, 1, Nothing)
        If Not targetElement Is Nothing Then
            Range("A1").Value = targetElement.SingleNodeValue.innerText
        End If
    End If
    
    ie.Quit
    Set ie = Nothing
End Sub

内容的提问来源于stack exchange,提问作者Osvaldo Assunção

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:52:18