【问题标题】:Web scraping with VBA - Early Binding VS Late Binding of HTMLDocument Object使用 VBA 进行 Web 抓取 - HTMLDocument 对象的早期绑定 VS 后期绑定
【发布时间】:2019-04-25 11:06:49
【问题描述】:

我正在尝试根据“https://finance.yahoo.com”设置自动更新股票价值。

我需要使用后期绑定,但它不起作用,而早期绑定可以正常工作。有办法解决吗?

 Sub FetchFinanceInfoLateBinding()

    Dim XMLReq As Object
    Dim HTMLDoc As Object
    Dim post As Object, I&

    Set XMLReq = CreateObject("Msxml2.ServerXMLHTTP.6.0")
    'Set HTMLDoc = CreateObject("MSXML2.DOMDocument.6.0")
    Set HTMLDoc = CreateObject("htmlfile")

    XMLReq.Open "GET", "https://finance.yahoo.com/quote/BABA/cash-flow?p=BABA", False
    XMLReq.send
    HTMLDoc.body.innerHTML = XMLReq.responseText

    Set post = HTMLDoc.getElementsByClassName("Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)")(0)
    Debug.Print post.innerText


End Sub


Sub FetchFinanceInfoEarlyBinding()

    Dim XMLReq As New XMLHTTP60
    Dim HTMLDoc As New HTMLDocument
    Dim post As Object, I&

    XMLReq.Open "GET", "https://finance.yahoo.com/quote/BABA/cash-flow?p=BABA", False
    XMLReq.send
    HTMLDoc.body.innerHTML = XMLReq.responseText


    Set post = HTMLDoc.getElementsByClassName("Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)")(0)
    Debug.Print post.innerText

End Sub

如前所述,我希望能够在设置此解决方案时使用后期绑定。

【问题讨论】:

  • 这是一个已知问题,后期绑定htmlfile使用的IE版本低于9,不支持.getElementsByClassName方法。

标签: html excel vba web-scraping


【解决方案1】:

@omegastripes 在 cmets 中提到:

后期绑定的htmlfile使用IE 9以下版本,不支持 .getElementsByClassName 方法

.

不过你可以用正则表达式:

Option Explicit
Public Sub FetchFinanceInfoLateBinding()
    Dim XMLReq As Object
    Dim HTMLDoc As Object
    Dim post As Object, I&

    Set XMLReq = CreateObject("Msxml2.ServerXMLHTTP.6.0")
    Set HTMLDoc = CreateObject("htmlfile")

    XMLReq.Open "GET", "https://finance.yahoo.com/quote/BABA/cash-flow?p=BABA", False
    XMLReq.send
    HTMLDoc.body.innerHTML = XMLReq.responseText

    MsgBox GetValue(XMLReq.responseText, """regularMarketPrice"":{""raw"":[0-9.]+,""fmt"":""(\d+\.\d+)""}")

End Sub
Public Function GetValue(ByVal inputString As String, ByVal sPattern As String) As String
    With CreateObject("vbscript.regexp")
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = sPattern
        If .test(inputString) Then
            GetValue = .Execute(inputString).item(10).SubMatches(0)
        Else
           GetValue = vbNullString
        End If
    End With
End Function

试试正则表达式here

【讨论】:

  • 此正则表达式解决方案有效。留给我的唯一一件事就是了解它是如何工作的,谢谢!
  • 该值存在于响应中的脚本标记中。我指定了一个正则表达式模式来查找与该模式匹配的字符串。我索引返回的匹配项以获得最新值所需的匹配项。
猜你喜欢
  • 2023-03-29
  • 2016-12-15
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多