Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

xpath - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...