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']
  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[@class='btn btn-primary']
//input[@placeholder='Full Name']
  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

  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

  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


7. Example XPath for  following-sibling


8. Example XPath for  preceding -sibling 


9. Example XPath to navigate to a parent element


10. Ancestor

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

11. Following


11. Child


11. Preceding


Leave a Reply

Your email address will not be published.