Alexander Sh
Alexander Sh

Reputation: 33

xpath to find preceding element

There is a structure like this:

<div "nothing unique there">
<img "repeating parameters">
<span>
    repeating text
</span>
<span>
    <span>
        <img class="unique name">
    </span>
    <span>
        <strong>Tools</strong>
    </span>
</span>
.
.

I need to find with XPath the <img "repeating parameters"> The only unique part in the code above is <img class="unique name">

I tried this and it didn't work:

//span/img[@class="unique name"]/preceding-sibling::img

Upvotes: 3

Views: 4480

Answers (2)

CiaPan
CiaPan

Reputation: 9571

The <img "repeating parameters"> is not a preceding sibling of the img element you found, but rather of its grand-parent <span>. Use just preceding::img instead of preceding-sibling::img.

Upvotes: 1

Thomas Weller
Thomas Weller

Reputation: 59208

IMHO, if you want to select an img, then that should be the main part of your XPath. So, let's start with

//img

Now, let's add the conditions for that img. It seems that there's spanfollowing, so let's add that as a condition:

//img[following-sibling::span]

Now, that can't be any span. It needs to contain another img.

//img[following-sibling::span//img]

And that img again, is not just any img, but it has some special attributes. Let's add them as a condition to the inner img:

//img[following-sibling::span//img[@class="unique name"]]

There you go. IMHO a nice and understandable XPath.


Of course it would also be possible to go to the unique img first as you did.

//span/img[@class="unique name"]

Then, don't forget to step outwards:

//span/img[@class="unique name"]/../..

After that you can move to the preceding sibling:

//span/img[@class="unique name"]/../../preceding-sibling::img

Upvotes: 3

Related Questions