Mohamed Elmahdi
Mohamed Elmahdi

Reputation: 87

XPath select elements between 2 certain elements

I have this html page:

<tr class="facts_label"></tr>
<tr class="facts_label"></tr>
<tr class="other_label"></tr>
<tr class="facts_label"></tr>
<tr class="facts_label"></tr>
<tr class="other_label"></tr>
<tr class="other_label"></tr>
<tr class="facts_label"></tr>
<tr class="facts_label"></tr>
<tr class="other_label"></tr>    # Select this
<tr class="other_label"></tr>    # Select this
<tr class="facts_label"></tr>
<tr class="other_label"></tr>
<tr class="other_label"></tr>

I want to select the tr elements with class "other_label" that are between the last 2 tr elements with class "facts_label"

I tried :

'//tr[@class="other_label" and (preceding-sibling::tr[@class="facts_label"][last()-1]) and (following-sibling::tr[@class="facts_label"][last()])]'

But this is what I got

<tr class="facts_label"></tr>
<tr class="facts_label"></tr>
<tr class="other_label"></tr>    # Got this
<tr class="facts_label"></tr>
<tr class="facts_label"></tr>
<tr class="other_label"></tr>    # Got this
<tr class="other_label"></tr>    # Got this
<tr class="facts_label"></tr>
<tr class="facts_label"></tr>
<tr class="other_label"></tr>    # Got this
<tr class="other_label"></tr>    # Got this
<tr class="facts_label"></tr>
<tr class="other_label"></tr>
<tr class="other_label"></tr>

Upvotes: 4

Views: 63

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92894

Xpath "trick":

//tr[ @class='other_label' and count(following-sibling::tr[@class='facts_label'])=1 ]

Upvotes: 4

Related Questions