Reputation: 101
Imagine an HTML snippet as follows:
<div>
<div class="content">test1</div>
</div>
<div>
<div class="content">test2</div>
</div>
<div>
<div class="content">test3</div>
</div>
and the xpath I'm using is //div[@class='content']
Now, I want to refer to the Second div element. What should I add to my xpath? TIA.
Upvotes: 5
Views: 20461
Reputation: 22647
Two solutions have been proposed so far, but none of them selects anything from the HTML snippet you show in the question. When simply wrapping it in a root element:
<root>
<div>
<div class="content">test1</div>
</div>
<div>
<div class="content">test2</div>
</div>
<div>
<div class="content">test3</div>
</div>
</root>
Both //div[@class='content'][2]
and //div[2][@class='content']
select nothing from that document. They both assume that the second predicate (between [
and ]
) is applied to an intermediate result sequence, but the second predicate is also applied to the nodes of the initial document tree. To select a subset of an "intermediate" result, use parentheses around the first part:
(//div[@class='content'])[2]
and the single result will be
<div class="content">test2</div>
More details
//div[@class='content'][2]
means:
Select all elements called
div
from anywhere in the document, but only the ones that have aclass
attribute whose value is equal to "content". Of those selected nodes, only keep those which are the seconddiv[@class = 'content']
element of their parent.
So, this expression would only select a result from the following document:
<root>
<div>
<div class="content">test1</div>
</div>
<div>
<div class="content">test2</div>
<div class="other">other</div>
<div class="content">MATCH</div>
</div>
<div>
<div class="content">test3</div>
</div>
</root>
//div[2][@class='content']
means:
Select all elements called
div
from anywhere in the document, but only the ones that are the second child of their parent. Of those selected nodes, only keep those which have aclass
attribute whose value is equal to "content".
Only producing a match given a document like
<root>
<div>
<div class="content">test1</div>
</div>
<div>
<div class="other">other</div>
<div class="content">MATCH</div>
</div>
<div>
<div class="content">test3</div>
</div>
</root>
Upvotes: 21