VBA - 搜索网站,返回类元素值

VBA - 搜索网站,返回类元素值

我创建了一个 VBA 脚本来从网站上的类元素值返回一个值,但是这在这个特定元素中不起作用。我相信这可能是因为网站要求在返回结果之前先“加载”页面。

目前有没有什么方法可以不打开浏览器就返回网站搜索值?

提前致谢。

Sub WebRequestExample()
    Dim url As String
    Dim xmlHttp As Object
    Dim html As Object
    Dim responseText As String
    Dim elements As Object
    Dim elementSpan As Object
    Dim ws As Worksheet
    Dim startTime As Double
    Dim timeoutSeconds As Integer
    ' Define the URL
    url = "https://www.dhl.com/au-en/home/tracking/tracking-express.html?submit=1&tracking-id=2818454203"
    ' Create a new XMLHTTP request
    Set xmlHttp = CreateObject("MSXML2.XMLHTTP")
    ' Open the URL
    xmlHttp.Open "GET", url, False
    xmlHttp.Send
    ' Get the response text
    responseText = xmlHttp.responseText
    ' Create a new HTML document
    Set html = CreateObject("htmlfile")
    html.Body.innerHTML = responseText
    ' Set timeout duration in seconds
    timeoutSeconds = 30
    startTime = Timer
    ' Wait for the specific div element by class name to appear
    Do
        Set elements = html.getElementsByClassName("c-tracking-result--delivery-headline level3")
        If elements.Length > 0 Then
            Set elementSpan = elements(0)
            Exit Do
        End If
        DoEvents
    Loop While Timer < startTime + timeoutSeconds
    If Not elementSpan Is Nothing Then
        ' Write the content of the specific div to a specific cell
        Set ws = ThisWorkbook.Sheets("Invoice_Template")
        ws.Range("k12").value = elementSpan.innerText
    Else
        ' Handle the case where the element is not found within the timeout period
    End If
    ' Clean up
    Set xmlHttp = Nothing
    Set html = Nothing
    Set elementSpan = Nothing
    Set ws = Nothing
End Sub

相关内容