Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get nth node in Selenium

I try to write xpath expressions so that my tests won't be broken by small design changes. So instead of the expressions that Selenium IDE generates, I write my own.

Here's an issue:

//input[@name='question'][7]

This expression doesn't work at all. Input nodes named 'question' are spread across the page. They're not siblings.

I've tried using intermediate expression, but it also fails.

(//input[@name='question'])[2]
error = Error: Element (//input[@name='question'])[2] not found

That's why I suppose Seleniun has a wrong implementation of XPath.

According to XPath docs, the position predicate must filter by the position in the nodeset, so it must find the seventh input with the name 'question'. In Selenium this doesn't work. CSS selectors (:nth-of-kind) neither.

I had to write an expression that filters their common parents:

//*[contains(@class, 'question_section')][7]//input[@name='question']

Is this a Selenium specific issue, or I'm reading the specs wrong way? What can I do to make a shorter expression?

like image 859
culebrón Avatar asked Jul 30 '10 07:07

culebrón


People also ask

How do you find the nth element in selenium?

You can use “tag:nth-of-type(n)”. It will select the nth tag element of the list.

How do you select the nth matching element for an XPath on a Web page using selenium Webdriver?

By adding square brackets with index. By using position () method in xpath.

How do you select the second element with the same XPath?

//div[@class='content'][2] means: Select all elements called div from anywhere in the document, but only the ones that have a class attribute whose value is equal to "content". Of those selected nodes, only keep those which are the second div[@class = 'content'] element of their parent.


2 Answers

Here's an issue:

//input[@name='question'][7]   

This expression doesn't work at all.

This is a FAQ.

[] has a higher priority than //.

The above expression selects every input element with @name = 'question', which is the 7th child of its parent -- and aparently the parents of input elements in the document that is not shown don't have so many input children.

Use (note the brackets):

(//input[@name='question'])[7]

This selects the 7th element input in the document that satisfies the conditions in the predicate.

Edit:

People, who know Selenium (Dave Hunt) suggest that the above expression is written in Selenium as:

xpath=(//input[@name='question'])[7]
like image 197
Dimitre Novatchev Avatar answered Oct 11 '22 14:10

Dimitre Novatchev


If you want the 7th input with name attribute with a value of question in the source then try the following:

/descendant::input[@name='question'][7]
like image 31
Dave Hunt Avatar answered Oct 11 '22 14:10

Dave Hunt