首页 > 解决方案 > VBA 错误 438 对象在尝试从网站抓取网页时不支持此属性或方法

问题描述

我在尝试使用 VBA 从网站获取元素时遇到问题,我在 StackOverflow 中搜索了这个问题,但我尝试过的任何答案都解决了我的问题。

我想获取元素Strong中的文本,但是这个元素进入了一个Div。

Sub StatusInvest()
Dim html As HTMLDocument
    
    Set html = New HTMLDocument
      
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://statusinvest.com.br/acoes/eua/aapl", False
        .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" 'to deal with potential caching
        .send
        html.body.innerHTML = .responseText
    End With
    
    Application.ScreenUpdating = False


Set v = html.getElementsByClass("info special w-100 w-md-33 w-lg-20")(0).Value = "00000"
Set test = valor.getElementsByTagName("Strong").innerText


Range("B1").Value = teste
Application.ScreenUpdating = True

End Sub

这是我要获取的元素: HTML 示例

标签: excelvbaweb-scraping

解决方案


  1. 您的方法名称错误 - 应该是getElementsByClassName.

  2. getElementsByTagName并且getElementsByClassName两者都返回元素的集合,无论是否有一个或多个,因此当您尝试获取strong元素时必须参考索引 0。

  3. innertextproperty 返回一个字符串,所以你不应该使用Setstatement 而只是 assign test

    Sub StatusInvest()
        Dim html As HTMLDocument
        Dim valor As Object
        Dim test As String
    
        Set html = New HTMLDocument
    
        With CreateObject("MSXML2.XMLHTTP")
            .Open "GET", "https://statusinvest.com.br/acoes/eua/aapl", False
            .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" 'to deal with potential caching
            .send
            html.body.innerHTML = .responseText
        End With
    
        Application.ScreenUpdating = False        
    
        Set valor = html.getElementsByClassName("special")(0)
        test = valor.getElementsByTagName("Strong")(0).innerText
    
        Range("B1").Value = test
        Application.ScreenUpdating = True
    End Sub
    

推荐阅读