Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath: How to select node with some attribute by index?

Tags:

I have several nodes with some particular attribute and I need to select one of them by index. For example I need to select second <div> with 'test' class - //div[@class='test'][2] doesn't work.

Is there a way to select node with some attribute by index ? How to do it?

like image 346
HongKilDong Avatar asked Apr 28 '11 12:04

HongKilDong


People also ask

How index is defined in XPath?

XPath index is defined as per specific nodes within the node-set for index by using selenium webdriver. We can also mention the index-specific node with the help of a number of indexes enclosed by []. The tag name element UI contains multiple child elements with tag name as li.

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.

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.


1 Answers

This is a FAQ.

In XPath the [] operator has a higher precedence (binds stronger) than the // pseudo-operator.

Because of this, the expression:

//div[@class='test'][2] 

selects all div elements whose class attribute is "test" and who (the div elements) are the second such div child of their parent. This is not what you want.

Use:

(//div[@class='test'])[2] 
like image 160
Dimitre Novatchev Avatar answered Oct 20 '22 01:10

Dimitre Novatchev