Selecting an element with xpath and Selenium
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 t开发者_StackOverflowo 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)
Yaaa for me. I think this is the best answer, but open to other solutions!
//a[contains(@class,'btnX') and span[text()='Sign in']]
For and operation the below point is important.
“and” is case-sensitive, you should not use the capital “AND”.
Syntax: //tag[XPath Statement-1 and XPath Statement-2]
Here you can also find many other ways to find Xpath in Selenium: https://www.swtestacademy.com/xpath-selenium/
精彩评论