我正在尝试根据“https://finance.yahoo.com”设置股票值(value)的自动更新。
我需要使用后期绑定(bind),它不起作用,而早期绑定(bind)工作得很好。有办法解决吗?
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
如前所述,我希望能够在设置此解决方案时使用后期绑定(bind)。
最佳答案
正如@omegastripes 在评论中提到的:
late bound htmlfile uses IE version below 9, which doesn't support .getElementsByClassName method
.
不过你可以用正则表达式表达出来:
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
关于html - 使用 VBA 进行网页抓取 - HTMLDocument 对象的早期绑定(bind)与后期绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55847870/