Get Nth Element Using XPath - When [N] Element Doesn't Work

There was already some discussion of the Nth element in XPath:

XPath query to get the nth instance of an element

Get the Nth child of a node using xpath

XPath and PHP: parse the nth instance of an element

I use Selenium and PHPUnit for functional testing. My problem is that on a page with a large form, the Nth selector does not work. I have 80 input fields (using Selenium's call getXpathCount ('// input') to get the exact number) - and I would like to iterate through 80 fields and type. What I already tried and did not work (N is an index variable):

//input[N] //input[position()=N] input[N] (//input)[N] (.//input)[N] css=input:nth-of-type(N) 

And all the mixtures are higher. Usually it triggers an Exception statement: the element was not found in N = 2. I tried several XPath tools for browsers, since native extensions like XPathEvaluator in Chrome - almost all gave me the correct results. Therefore, Seleniums XPath parser seems to work a little differently.

What do you think? Am I missing the main thing?

Update: Here is my solution: getAllFields (): http://release.seleniumhq.org/selenium-remote-control/0.9.0/doc/java/com/thoughtworks/selenium/DefaultSelenium.html#getAllFields () , and then I repeat.

Actually this does not solve the original problem, so I am still interested in the answer.

Thanks!

+4
source share
4 answers

(//input)[15] returns the 15th input element in the document

//input[15] returns each input element, which is the 15th child of the parent element.

So, some of your expressions are at least incorrect. But they are not all wrong, so I do not know why it does not work for you.

+10
source

Without seeing your specific code and HTML, we mostly guess here. But xpath=(//input)[2] will find the second input field on the page, regardless of where it is located. Be sure to include xpath= because Selenium RC does not accept it unless the locator starts with // . Also note that in XPath, n starts with 1, not 0, as in C.

+3
source

This worked for me:

/descendant::input[@id="search_query"][2]

See also this answer.

+1
source

I do not use PHPUnit, but I love XPath.

In the Safari Inspector search box:

 //input[N] 

or scope:

 //div/input[N] means second input in a div (//div/input)[N] means second div that has an input (select the first input) 
-1
source

All Articles