Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xpath to find preceding element

Tags:

xpath

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
like image 667
Alexander Sh Avatar asked Feb 14 '26 08:02

Alexander Sh


1 Answers

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
like image 192
Thomas Weller Avatar answered Feb 17 '26 01:02

Thomas Weller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!