KimoUSA
KimoUSA

Reputation: 1

Why is my XPath based on text content failing?

I'm trying to match this a link:

<a href="/collection/accessories_wall?productType=Cases+%26+Sleeves&amp;productType=Screen+Protectors&amp;compatibilityCategory=Phone" class="product-link" data-product-id="cases_protection" xpath="1">
  Cases &amp; protection
  
</a>

Tried:

//a[contains(text(),'Cases &amp; protection')]

Upvotes: 0

Views: 35

Answers (2)

zx485
zx485

Reputation: 29022

You probably forgot to escape the ampersand & with &amp;.
So try this instead:

//a[contains(normalize-space(text()),'Cases &amp; protection')]

EDIT:
I added the normalize-space(...) function to only check the core text and not the surrounding spaces. Maybe that does help you.

Upvotes: 1

kjhughes
kjhughes

Reputation: 111541

What you have is fine as posted, but here are some common reasons that XPath's intending to match on element text might fail:

  1. Additional markup such as <b></b> thwarts tests of text() node children.
    Remedy: Test the string-value of the element:

    //a[contains(.,'Cases &amp; protection')]
    
  2. Whitespace causes comparison failure.
    Remedy: Use normalize-space():

    //a[contains(normalize-space(),'Cases &amp; protection')]
    
  3. False positive matches arise because other strings match on a substring-basis:
    Remedy: Test for equality rather than substring containment:

    //a[normalize-space()='Cases &amp; protection']
    

Webpage-related issues for unexpected failures for an XPath to match (apart from text content testing) include markup/content not having loaded yet, being dynamically generated, or residing in an iframe.

Upvotes: 0

Related Questions