Select the nth matched node from the list of matching nodes

I work with selenium to do some automation, and I'm trying to interact with my webpage using Selenium and CSS selectors.

My question is: how to select the nth matched node returned from the list of all matching nodes?

For example, my CSS selector is ".contactName", which returns 2 matching nodes. Using Selenium I want to do something like

selenium.Click("css=.contactName the second match"); 

Any help is greatly appreciated.

+2
source share
2 answers

Here is what I ended up using to select the second input with the class name

 selenium.Click("xpath=(//input[@class='contactName'])[2]"); 
+4
source

Are these two nodes connected to the same parent? If so, you can try one of them, depending on where they are under the parent in the DOM, and if there are any other elements:

 selenium.Click("css=.contactName:nth-child(2)"); selenium.Click("css=.contactName + .contactName"); selenium.Click("css=.contactName ~ .contactName"); 

If these two nodes do not have the same parent, you will most likely have to use the XPath locator instead of CSS:

 selenium.Click("xpath=//*[@class='contactName'][2]"); 
+2
source

All Articles