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!
(//input)[15] returns the 15th input element in the document
(//input)[15]
//input[15] returns each input element, which is the 15th child of the parent element.
//input[15]
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.
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.
xpath=(//input)[2]
xpath=
//
n
This worked for me:
/descendant::input[@id="search_query"][2]
See also this answer.
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)