How to write XPath for multiple sibling of div tag

Viewed 442

I am writing XPath for the following piece of code:

<div class="line info">
        <div class="unit labelInfo TextMdB">First</div>
        <div class="unit lastUnit">
                <div class="line TextMd">Second</div>

How can I reach the second div tag by using the first div tag using the sibling concept? I wrote my XPath like:

//div[contains(text(), 'First')]/following-sibling::div[2][contains(text(),'Second')]

But it's not working. How do I reach the "second" by using the "first" div tag? I appreciate your help.

1 Answers
//div[contains(text(), 'First')]/following-sibling::div[2]
--------------------------------------------------------^

There is no 2nd "following sibling" at this point. The <div> that contains the text 'Second' is a child of the div.unit.lastUnit.

This means

//div[contains(text(), 'First')]/following-sibling::div[1]/div[contains(text(),'Second')]

Another way that is less dependent on document structure would be to say "I want the first following <div> that contains the the text 'Second'":

(//div[contains(text(), 'First')]/following::div[contains(text(),'Second')])[1]

but this might return results you did not want, exactly because it pays less attention to document structure.

Related