Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 to find an element, and what can I do to get it to work?

like image 990
cgp Avatar asked Apr 27 '11 18:04

cgp


2 Answers

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>

like image 200
Emiliano Poggi Avatar answered Nov 20 '22 17:11

Emiliano Poggi


//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)

like image 5
Ardesco Avatar answered Nov 20 '22 17:11

Ardesco