Search code examples
vbaexcelweb-scrapinginnerhtml

How to fetch data inside <b> tag while web scraping in VBA


I am trying to scrape data from this website. i have written the code which opens this website and then searches for a value. clicks on the search result and opens the final page from where i have to pick the details. i need to pick details of tag mentioned in red in

this image

this is my code which opens the desired page. I have used Link.click to open the desired page. After that i need to fetch details mentioned in image. Kindly advise.

Sub hullByAshish()
Dim html, html1 As HTMLDocument
Dim ElementCol, ElementCol1 As Object
Dim Link As Object
Dim appIE As Object
Dim a As String
Dim i As Long
Dim objElement As Object
Dim objCollection As Object
Set appIE = CreateObject("internetexplorer.application")
a = "PONTOVREMON"
With appIE
    .Navigate "https://www.marinetraffic.com/en/ais/index/search/all/keyword:" & a
    .Visible = True
End With
Do While appIE.Busy
    DoEvents
Loop
Application.Wait (Now() + TimeValue("00:00:01"))
Set html = appIE.document
Set ElementCol = html.getElementsByTagName("a")
DoEvents
For Each Link In ElementCol
If Link.innerHTML = "PONTOVREMON" Then
Link.Click
End If
Next Link
End Sub

Solution

  • Here is one way

    Dim ie As Object, ieDoc As Object, lnk As Object
    
    Sub hullByAshish()
        Dim IMO As String, MMSI As String, GTon As String
    
        Set ie = CreateObject("internetexplorer.application")
    
        a = "PONTOVREMON"
    
        With ie
            .Navigate "https://www.marinetraffic.com/en/ais/index/search/all/keyword:" & a
            .Visible = True
        End With
    
        Do While ie.readystate <> 4: Wait 5: Loop
    
        DoEvents
    
        Set ieDoc = ie.document
    
        For Each lnk In ieDoc.getElementsByTagName("a")
            If lnk.innerhtml = "PONTOVREMON" Then
                lnk.Click
                Exit For
            End If
        Next lnk
    
        Do While ie.readystate <> 4: Wait 5: Loop
    
        IMO = GetValue("IMO:")
        MMSI = GetValue("MMSI:")
        GTon = GetValue("Gross Tonnage:")
    
        Debug.Print "IMO: " & IMO
        Debug.Print "MMSI: " & MMSI
        Debug.Print "Gross Tonnage: " & GTon
    End Sub
    
    Function GetValue(s As String) As String
        GetValue = Trim(Split(Split(Split(Trim(Split(ie.document.body.innerhtml, s)(1)))(0), "<b>")(1), "</b>")(0))
    End Function
    
    Private Sub Wait(ByVal nSec As Long)
        nSec = nSec + Timer
        While nSec > Timer
            DoEvents
        Wend
    End Sub
    

    Screenshot

    enter image description here