I have HTML which looks basically like the following:
...
<a class="btnX btnSelectedBG" href="#"><span>Sign in</span></a>
...
The following xpath in Selenium fails to find an element:
//a[contains(text(), 'Sign in') and contains(@class,'btnX')]
The following xpaths in Selenium succeed, but are not specific enough for me.
//a[contains(text(), 'Sign in')]
//a[contains(@class, 'btnX')]
Why is the xpath failing to find an element, and what can I do to get it to work?
Match cases where Sign in
is directly child of a
or child of another element:
//a[contains(@class,'btnX') and .//text()='Sign in']
I mean
<a class="btnX btnSelectedBG" href="#">Sign in</a>
and
<a class="btnX btnSelectedBG" href="#"><b>Sign in</b></a>
//a[contains(@class,'btnX') and span[text()='Sign in']] is not a good idea because you are going to search through the DOM for every anchor and then try and compary it to your search criteria.
You ideally want to key your XPath to the first ascendant element that has an ID and then work your way down the tree.
e.g. if your html is
<div id="foo">
<a class="btnX btnSelectedBG" href="#"><span>Sign in</span></a>
</div>
You could use:
//div[@id='foo']/a[contains(@class, 'btnX')][span[.='Sign in']]
Unfortunatly I don't know the rest of the structure of the page so I can't give you anything more concrete than:
//a[contains(@class, 'btnX')][span[.='Sign in']]
but it is really not a very nice xpath.
(My XPath's look slightly different to you because I have used . as a shortcut for text() and a second set of [] as a shortcut for and)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With