Selecting an element with xpath and Selenium

cgp picture cgp · Apr 27, 2011 · Viewed 47.1k times · Source

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?

Answer

Emiliano Poggi picture Emiliano Poggi · Apr 27, 2011

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>