Search code examples
vbaseleniumloopsxpathpredicate

Selenium VBA XPath with variable predicate loop


I am hoping for some help with syntax in Selenium VBA.

I am trying to scrape some table date using a variable predicate 'r' to specify the row like this but it does not work.

The code does work when an integer value is put in in place of a predicate 'r' [I think predicate is the right word from looking around] so I know that the expression is finding the right thing.

For r = 2 To 4

ThisWorkbook.Sheets("Orders").Cells(r, 1).Value = bot.FindElementByXPath("//*[@id='ctl00_mainContent_ucOrdersList_dgOrders']/tbody/tr[r]/td[2]").Text

Next r

It seems as though it should be possible. I found this but am not sure what language it is or how to translate it into Selenium VBA:

for (int i =1;i<rows.size();i++)
            {    
                max= wd.findElement(By.xpath("html/body/div[1]/div[5]/table/tbody/tr[" + (i+1)+ "]/td[4]")).getText();

So in essence how do I do the tr[" + (i+1)+ "] bit in Selenium VBA?

Thanks in advance.


Solution

  • Try this in your loop:

    ThisWorkbook.Sheets("Orders").Cells(r, 1).Value = bot.FindElementByXPath("//*[@id='ctl00_mainContent_ucOrdersList_dgOrders']/tbody/tr[" & r & "]/td[2]").Text
    

    Use ampersand & to join strings.

    This is the key bit: "...tr[" & r & "]/td..."

    More info on joining strings in vb here

    For the + operator, they state:

    Although in principle the + sign is identical to the & concatenation operator, it also doubles as the addition operator. Hence, as Microsoft states:

    When you use the + operator, you may not be able to determine whether addition or string concatenation will occur. Use the & operator for concatenation to eliminate ambiguity and provide self-documenting code.