XPath locators in Selenium Webdriver



If you have been using webdriver you would know the paramount nature of Xpath! I have a lot of colleagues who start googling every-time they get stuck with trying to find an element.

Some classic examples are:

Xpath to find the occurrence of a webelement with same properties or attributes:
//*[@name='Test'])[3]
We are finding the third occurrence where the name attribute is Test
Remember: The [] operator has higher precedence (priority) than the // abbreviation.

//div[text()='phys_tag_desc']
If the text is not exact match. Try following:
//div[contains(text(),'phys_tag_desc')]

Radio Buttons - //input[@value='2']

iFrames - //iframe[@id='iframePage']

Here is an exhaustive list that will help you for sure:

Whole web page xpath=/html 

Whole web page body xpath=/html/body
Element with id 'Test' 
//Element [@id='test'] 
Any element with id test
//*[@id='test'] 

Second element anywhere on page
xpath=(//element)[2] 

Image element //img
Element with attribute containing text 'test'
//Element[contains(@attribute,'test')

Element whose attribute starts with 'test'
//Element[starts-with(@attribute, 'test')] 

Element1 with id A or element2 with id B
//Element1[@id='A'] | //Element2[@id=B] 

Element with id A or id B
//E1[@id='A' or @id='B']

Element with name N & specified value ‘v’ 
//*[@name='N'][@value='v'

Link element //a 

containing text 't' exactly
//a[.='t']

with target link 'url'
//a[@href='url'] 

First child of element  
//E/*[1] 
First child 
//E[1] 

Last child of element E 
//E/*[last()] 

Last child 
//E[last()] 

Element with no children 
//E[count(*)=0] 
Element with an only child 
//E[count(*)=1

Cell by row and column (e.g. 3rd row, 2nd column) 
//*[@id='TestTable']//tr[3]//td[2] 
//*[@id='TestTable'].2.1 } 
Cell immediately following cell containing 't' exactly 
//td[preceding-sibling::td='t'] 
Cell immediately following cell containing 't' 
//td[preceding-sibling::td[contains(.,'t')]] 

User interface element that is disabled 
//E[@disabled] 
User interface element that is enabled 
//*[not(@disabled)] 
Checkbox (or radio button) that is checked 
//*[@checked] 
Enjoy XPathing :) 

Comments

Popular posts from this blog

Software Testing @ Microsoft

Trim / Remove spaces in Xpath?