Excel VBA - Web Scraping - Testo interno della cella della tabella HTML

Sep 04 2020

Sto cercando di creare una macro per raschiare sul Web lo stato di una spedizione di carico in base al numero di spedizione. Sto utilizzando il metodo XML-HTTP ma sono nuovo nel web scraping VBA. Ho provato a ottenere il valore utilizzando GetValuebyID, Tag, Class senza successo.

La linea evidenziata è quella da cui ho bisogno del valore estratto. [Necessità di estrarre il valore 10 di 10 fornito] [1]

Questo è quanto sono arrivato lontano con il codice.

Sub FlightStat()

Dim XMLReq As New MSXML2.XMLHTTP60
Dim HTMLDoc As New MSHTML.HTMLDocument
Dim AllTables As IHTMLElementCollection
Dim MainTable As IHTMLTable


XMLReq.Open "GET", "https://www.unitedcargo.com/OurNetwork/TrackingCargo1512/Tracking.jsp?id=10205436&pfx=016", False

XMLReq.send

If XMLReq.Status <> 200 Then
    MsgBox "Problem" & vbNewLine & XMLReq.Status & " - " & XMLReq.statusText
    Exit Sub
End If

HTMLDoc.body.innerHTML = XMLReq.responseText

Set AllTables = HTMLDoc.getElementsByTagID("dispTable0")

  

End Sub

Sarei grato se qualcuno potesse aiutarmi a ottenere il valore "10 di 10 Delivered" estratto [1]: https://i.stack.imgur.com/xcOAZ.png

Risposte

1 Zwenn Sep 04 2020 at 11:58

Ok, come ho scritto nel mio commento. Puoi raschiare lo stato con IE.

Nota: il codice seguente non ha timeout integrato se il contenuto dinamico non può essere caricato. Inoltre, non viene verificato se il numero passato nell'URL è corretto.

Sub FlightStat()

Dim url As String
Dim ie As Object
Dim nodeTable As Object

  'You can handle the parameters id and pfx in a loop to scrape dynamic numbers
  url = "https://www.unitedcargo.com/OurNetwork/TrackingCargo1512/Tracking.jsp?id=10205436&pfx=016"

  'Initialize Internet Explorer, set visibility,
  'call URL and wait until page is fully loaded
  Set ie = CreateObject("InternetExplorer.Application")
  ie.Visible = False
  ie.navigate url
  Do Until ie.readyState = 4: DoEvents: Loop
  
  'Wait to load dynamic content after IE reports it's ready
  'We can do that in a loop to match the point the information is available
  Do
    On Error Resume Next
    Set nodeTable = ie.document.getElementByID("dispTable0")
    On Error GoTo 0
  Loop Until Not nodeTable Is Nothing
  
  'Get the status from the table
  MsgBox Trim(nodeTable.getElementsByTagName("li")(2).innertext)
  
  'Clean up
  ie.Quit
  Set ie = Nothing
  Set nodeTable = Nothing
End Sub