Why Won't My Xpath Select Link/button Based On Its Label Text?
Solution 1:
Other answers have missed the actual problem here:
- Yes, you could match on
@title
instead, but that's not why OP's XPath is failing where it may have worked previously. - Yes, XML and XPath are case sensitive, so
Home
is not the same ashome
, but there is aHome
text node as a child ofa
, so OP is right to useHome
if he doesn't trust@title
to be present.
Real Problem
OP's XPath,
//a[contains(text(), 'Home')]
says to select all a
elements whose first text node contains the substring Home
. Yet, the first text node contains nothing but whitespace.
Explanation:text()
selects all child text nodes of the context node, a
. When contains()
is given multiple nodes as its first argument, it takes the string value of the first node, but Home
appears in the second text node, not the first.
Instead, OP should use this XPath,
//a[text()[contains(., 'Home')]]
which says to select all a
elements with any text child whose string value contains the substring Home
.
If there weren't surrounding whitespace, this XPath could be used to test for equality rather than substring containment:
//a[text()[.='Home']]
Or, with surrounding whitespace, this XPath could be used to trim it away:
//a[text()[normalize-space()= 'Home']]
See also:
Solution 2:
yes you are doing 2 mistakes, you're writing Home
with an uppercase H when you want to match home
with a lowercase h. also you're trying to check the text content, when you want to check check the "title" attribute. correct those 2, and you get:
//a[contains(@title, 'home')]
however, if you want to match the exact string home
, instead of any a that has home
anywhere in the title attribute, use @zsbappa's code.
Solution 3:
You can try this XPath..Its just select element by attribute
//a[@title,'home']
Post a Comment for "Why Won't My Xpath Select Link/button Based On Its Label Text?"