Search code examples
vbaselenium-webdriverhtml-tableexcel-2010

I need data from the second table with the same classname with VBA Selenium


I want to get some data from a webpage. I need data from two tables, but both have the same class name.

I cant get item(2) working.

I am not new to VBA, but new to Selenium.

I am able to get data from the first table, not from the second one. I search several websites, but no working solution yet.

Sub GetData()

Dim DRow As Byte
Dim DCol As Byte

    Dim WebDrv As New WebDriver

        Dim tr As Object
        Dim td As Object

WebDrv.Start "Chrome"
WebDrv.Get "https://stripinfo.be/reeks/strip/11316_Jeremiah_5_Het_eindeloos_experiment"

Application.Wait Now + TimeValue("00:00:1")

[D7] = WebDrv.FindElementByClass("title").Text

DRow = 8
DCol = 4

For Each tr In WebDrv.FindElementByClass("innerDividers").FindElementByTag("tbody").FindElementsByTag("tr")

    For Each td In tr.FindElementsByTag("td")
        Cells(DRow, DCol).Value = td.Text
        DCol = DCol + 1
    Next td
    DRow = DRow + 1
    DCol = 4

Next tr

DRow = 15

For Each tr In WebDrv.FindElementByClass("innerDividers").FindElementByTag("tbody").FindElementsByTag("tr")

    For Each td In tr.FindElementsByTag("td")
        Cells(DRow, DCol).Value = td.Text
        DCol = DCol + 1
    Next td
    DRow = DRow + 1
    DCol = 4

Next tr

Application.Wait Now + TimeValue("00:00:1")

End Sub

Solution

  • Some options:

    1. Change to a method returning webElements and index into the referenced collection, or use the For Each enumerator:
    Dim tables As Selenium.WebElements, table As Selenium.Table, t As Long
    
    Set tables = WebDrv.FindElementsByClass("innerDividers")
    
    For Each table in tables
        'do something with table here
    
        If t = 1 Then Exit For
        t = t + 1
    Next
    
    1. You could also use a CSS selector list to get only those 2 tables

    Set tables = WebDrv.FindElementsByCss("section:nth-child(2) div:nth-child(3) div:nth-child(-n+3) table")
    

    The latter is likely less robust over time but more efficient for a short term project.

    Pick your poison.