Home > Blockchain >  VBA Selenium - count the xPath Text occurrence
VBA Selenium - count the xPath Text occurrence

Time:10-21

Part of my data extraction is using XPath to find the text name. Then it looks up the text name in a worksheet to find the row number. Two other XPath data are extracted and added to the row number.

The problem is the webpage contains 4 occurrences of the same word "Duet" so the first occurrence of the Text Name (same row number) is overwritten 4 times

I know Count will tell me that there is 4 occurrence of the word "Duet".

Is there a way I can find if the particular XPath text name is the 1st, 2nd, 3rd or 4th occurrence of the text "Duet"?

    'Find Name
DIV_Name = .FindElementByXPath("/html/body/ui-view/main/div[1]/div[1]/ui-view/div/ui-view/div[4]/div/section/table[2]/tbody/tr[3]/td[1]").Text
TRow = Sheets("Import").Range("A:A").Find(what:=DIV_Name, LookIn:=xlValues, LookAt:=xlWhole).row

'Extract data
MyString = .FindElementByXPath("/html/body/ui-view/main/div[1]/div[1]/ui-view/div/ui-view/div[4]/div/section/table[2]/tbody/tr[3]/td[2]").Text
Sheets("Import").Range("G" & TRow) = MyString

'Extract data
MyString = .FindElementByXPath("/html/body/ui-view/main/div[1]/div[1]/ui-view/div/ui-view/div[4]/div/section/table[2]/tbody/tr[3]/td[3]").Text
            Sheets("Import").Range("H" & TRow) = MyString

CodePudding user response:

You can create XPath like

//*[text()="Duet"]

you can pass index which occurrence you need, for example, you need the first occurrence then pass

(//*[text()="Duet"])[1]

CodePudding user response:

count the xPath Text occurrence

You can use the findElements method to count the occurrences. In below example, you may need to change the xPath based upon your requirement.

Code#1:

 r = .FindElementsByXPath("//*[text()='Duet']").Count
 Debug.Print r

Output#1:

4

Is there a way I can find if the particular XPath text name is the 1st, 2nd, 3rd or 4th occurrence of the text "Duet"?

Code#2:

For i = 1 To r
    MyString = .FindElementByXPath("(//*[text()='Duet'])[" & i & "]").Text
    Debug.Print MyString & " text at xPath " & i
Next i

Output#2:

Duet text at xPath 1
Duet text at xPath 2
Duet text at xPath 3
Duet text at xPath 4
  • Related