Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select specified node within Xpath node sets by index with Selenium?

Tags:

selenium

xpath

I'm writing a Selenium testcase. And here's the xpath expression I use to match all 'Modify' buttons within a data table.

//img[@title='Modify'] 

My question is, how can I visit the matched node sets by index? I've tried with

//img[@title='Modify'][i] 

and

//img[@title='Modify' and position() = i] 

But neither works.. I also tried with XPath checker(One firefox extension). There're totally 13 matches found, then I have totally no idea how am I gonna select one of them.. Or does XPath support specified selection of nodes which are not under same parent node?

like image 927
Kymair Wu Avatar asked Sep 09 '10 07:09

Kymair Wu


People also ask

Can you use XPath expression used to select the target node and its values?

XPath assertion uses XPath expression to select the target node and its values. It compares the result of an XPath expression to an expected value. XPath is an XML query language for selecting nodes from an XML. Step 1 − After clicking Add Assertion, select Assertion Category – Property Content.


2 Answers

This is a FAQ:

//someName[3] 

means: all someName elements in the document, that are the third someName child of their parent -- there may be many such elements.

What you want is exactly the 3rd someName element:

(//someName)[3] 

Explanation: the [] has a higher precedence (priority) than //. Remember always to put expressions of the type //someName in brackets when you need to specify the Nth node of their selected node-list.

like image 108
Dimitre Novatchev Avatar answered Sep 24 '22 17:09

Dimitre Novatchev


There is no i in XPath.

Either you use literal numbers: //img[@title='Modify'][1]

Or you build the expression string dynamically: '//img[@title='Modify']['+i+']' (but keep in mind that dynamic XPath expressions do not work from within XSLT).

Or does XPath support specified selection of nodes which are not under same parent node?

Yes: (//img[@title='Modify'])[13]


This //img[@title='Modify'][i] means "any <img> with a title of 'Modify' and a child element named <i>."

like image 37
Tomalak Avatar answered Sep 20 '22 17:09

Tomalak