Selenium / Appium Xpath Techniques and Examples

Yosuva ArulanthuXPATHLeave a Comment

  1. Basic XPath starts with a star (*)

The XPath starts with //* helps to find any matching the attribute specified

Sample XPath To find any element using its attributes/properties

//*[@class='btn btn-primary']
//*[@id='submit']
//*[@name='username']
  1. Basic XPath starts with a tag name (button,input,a and etc)

If we are not getting unique elements using //* and attribute, we can filter further using the tag name

Sample XPath To find a specific type of element using its tag name and attributes/properties

//button[@id='submit']
//button[@class='btn btn-primary']
//input[@value='Login']
//input[@placeholder='Full Name']
//button[text()='Submit']
//a[@href='https://yosuva.com']
  1. Contains

Contains() method can be used in an XPath expression when the value of any attribute changes dynamically. The contains feature has the ability to find the element with partial text 

Sample Xpath with contains keyword

//button[contains(text(),'Sub')]
//input[contains(@id,'user')]
  1. XPath Using OR & AND

In OR condition, two conditions are used, either the first condition OR second condition should be true. 

In AND condition, two conditions are used, the first condition AND second condition should be true. 

Sample XPath using ‘and’ , ‘or’ condition

//input[@placeholder='Full Name' and @id='userName']
//input[@placeholder='Full Name' or @id='userName']
  1. Starts-With

Starts-with function helps to the element whose attribute value changes on refresh or any operation on the webpage.

Example XPath for  starts with keyword

//input[starts-with(@id,'userEmail')]
  1. Using Index

This approach can be used when you find more than one element with a specific attribute.If it is more than one, You can filter it further using the index value

(//input[@type=”text”)[2]

7. Example XPath for  following-sibling

//div[@class='userName']/following-sibling::div/input

8. Example XPath for  preceding -sibling 

//div[@class='userName']/preceding-sibling::div/label

9. Example XPath to navigate to a parent element

//div[@class='userName']/..
//*[@id='rt-feature']//parent::div

10. Ancestor

//*[text()='First Name']//ancestor::div[1]

11. Following

//*[@type='text']//following::input

11. Child

//*[@id='name_tech']//child::li

11. Preceding

//*[@type='submit']//preceding::input

Leave a Reply

Your email address will not be published.