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

如何修复VBA中getElementsByClassName获取网页价格时的错误91?

错误91的原因及解决方案

问题根源

错误91(对象变量或With块变量未设置)的核心原因是:你用MSXML2.XMLHTTP请求到的是静态初始HTML,而目标价格元素是网页通过JavaScript动态渲染生成的,静态HTML中根本不存在sc-be365e-0 bqZvXY这类动态类名的元素,导致getElementsByClassName返回空集合,Item(0)自然无法引用有效对象。

另外补充:这类React/Vue构建的单页应用,动态类名(如sc-be365e-0)是框架自动生成的,随时可能随网站更新变化,靠类名定位元素本身就不稳定。


解决方案一:用IE浏览器加载并等待渲染(简单直接)

通过IE浏览器完整加载页面(包括JavaScript渲染),再提取元素:

  1. 先在VBA编辑器中启用引用:工具 → 引用,勾选Microsoft Internet Controls
  2. 替换代码如下:
Sub Get_Web_Data_IE()
    Dim ie As New InternetExplorer
    Dim html As HTMLDocument
    Dim priceElement As Object
    Dim website As String
    
    website = "https://app.pulsex.com/info/token/0xa1077a294dde1b09bb078844df40758a5d0f9a27"
    
    ' 初始化IE,调试时设为True可见,发布时可改False
    ie.Visible = True
    ie.Navigate website
    
    ' 等待页面完全加载(含JS渲染)
    Do While ie.Busy Or ie.ReadyState <> READYSTATE_COMPLETE
        DoEvents
    Loop
    
    Set html = ie.Document
    
    ' 用querySelector简化元素定位(类名需和当前页面一致)
    Set priceElement = html.querySelector(".sc-be365e-0.bqZvXY")
    
    If Not priceElement Is Nothing Then
        Range("A1").Value = priceElement.innerText
    Else
        MsgBox "未找到价格元素,请检查类名是否已更新"
    End If
    
    ' 关闭IE并释放对象
    ie.Quit
    Set ie = Nothing
End Sub

解决方案二:调用API接口(高效稳定,推荐)

Pulsex这类DeFi平台通常提供公开API,直接请求数据比解析HTML更可靠,也避免了类名变化的问题。以下是示例代码(需确认API地址及返回结构,若平台API有更新需调整):

Sub Get_Price_By_API()
    Dim request As Object
    Dim response As String
    Dim price As String
    Dim apiUrl As String
    
    ' Pulsex代币信息API地址(需确认当前有效)
    apiUrl = "https://api.pulsex.com/api/v1/token/0xa1077a294dde1b09bb078844df40758a5d0f9a27"
    
    Set request = CreateObject("MSXML2.XMLHTTP")
    request.Open "GET", apiUrl, False
    request.setRequestHeader "Content-Type", "application/json"
    request.send
    
    If request.Status = 200 Then
        response = request.responseText
        ' 从JSON响应中提取价格(这里假设响应含"price":"0.00014"格式)
        price = Mid(response, InStr(response, """price"":""") + 8, _
                    InStr(InStr(response, """price"":""") + 8, response, """") - (InStr(response, """price"":""") + 8))
        Range("A1").Value = price
    Else
        MsgBox "API请求失败,状态码:" & request.Status
    End If
    
    Set request = Nothing
End Sub

若需要更规范的JSON解析,可安装VBA-JSON库,直接解析JSON结构获取价格。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 15:57:10