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?
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.
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.
//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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With