xPath help > Find img with alt='My Keyword'

12,876

Solution 1

Use:

boolean(//img[contains(@alt, 'yourKeywordHere')])

to find (true(), false()) whether there is an img element in the XML document whose alt attribute contains 'yourKeywordHere'.

Use:

boolean(//yourTag//img[contains(@alt, 'yourKeywordHere')])

to find if there is an element in the document named yourTag that has a descendent img whose alt attribute contains 'yourKeywordHere'.

Solution 2

I don't understand exactly what elements you are loooking for, but here is the example, which returns all elements h1 which contains at least one image with your_keyword in alt:

//h1[.//img[contains(@alt, 'your_keyword')]]

You should also handle if it is case sensitive or not. You can use this xpath but be careful, some xpath evaluators doesn't support lower-case function.

//h1[.//img[contains(lower-case(@alt), lower-case('your_keyword'))]]

Here is example:

//h1[.//img[contains(@alt, 'key ')]]

<html>
    <h1> <!-- found -->
        <img alt='here is my key' />
    </h1>
    <h1><!-- not found -->
        <img alt='here is not' />
    </h1>
    <h1> <!-- found -->
        <h2>
            <img alt='the key is also here' />
        </h2>
    </h1>
    <h1></h1> <!-- not found -->

</html>
Share:
12,876
Scott B
Author by

Scott B

Updated on June 05, 2022

Comments

  • Scott B
    Scott B about 2 years

    How can I alter this xpath to find if the content contains an img tag with an alt containing my keyword phrase?

    $xPath->evaluate('count(/html/body//'.$tag.'[contains(.,"'.$keyword.'")])');