Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath selector by class AND index

Tags:

xpath

I have the following HTML:

<div>
  <p>foo</p>
  <p class='foo'>foo</p>
  <p class='foo'>foo</p>
  <p>bar</p>
</div>

How can i select second P tag with class 'foo' by XPath?

like image 743
hoblin Avatar asked Nov 09 '11 11:11

hoblin


People also ask

Can we use index in XPath?

In index, we can write the expression of XPath with the braces, and then we can write the index outside into the braces. It is defined as per specific nodes within the node-set for XPath index by using selenium webdriver.

Can I use class in XPath?

Xpath class is defined as a selector that is usually shared by multiple elements in the document means it extracts all the class names. Nodes or lists of nodes are selected using XPath expressions based on property class names. The class name is separated by a Spaces. This token has white space.

How do I find the XPath of a div tag?

Just right click on the element of the webpage and select inspect element. If the XPath is correct, then the desired element will be highlighted, and you can use this as a locator in your automation test.

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

For example if both text fields have //input[@id='something'] then you can edit the first field xpath as (//input[@id='something'])[1] and the second field's xpath as (//input[@id='something'])[2] in object repository.


1 Answers

The following expression should do it:

//p[@class="foo"][2]

Edit: The use of [2] here selects elements according to their position among their siblings, rather than from among the matched nodes. Since both your tables are the first children of their parent elements, [1] will match both of them, while [2] will match neither. If you want the second such element in the entire document, you need to put the expression in brackets so that [2] applies to the nodeset:

(//p[@class="foo"])[2]
(//table[@class="info"])[2]
like image 118
lonesomeday Avatar answered Sep 20 '22 14:09

lonesomeday