What is XPath and why it is needed?
It is a syntax for finding any element on the web page using XML path expression. It is used when elements cannot be found using common locators like id, class, name, etc.
Format of XPath: //tagname[@attribute=’value’]
Types of XPath:
- Absolute Xpath:
It is the direct way to determine the element from the root node. The disadvantage of this method is if any element in the path is deleted or any element is added then path gets altered, and element won’t get identified.
- Relative XPath:
This is the most commonly used way to build the XPath and identify the element. Xpath can be built from anywhere in HTML DOM, hence the size of the XPath is shorter and won’t get altered very frequently.
Some of the most commonly used functions to identify elements
Contains ():
Contains is a method used in constructing XPath expression. It is used when the element needs to be determined by its text or by partial text.
Ex:

Element ‘Gmail’ can be determined using Contains method and using attribute as text by the below syntax
Xpath = “//a[contains(text(),’Gmail’)]”
AND or OR:

Using AND expression, both the condition must be true to identify the element. Even if one of the condition fails then element won’t be determined.
To be able to recognize the element ‘Gmail’, both the condition has to be valid.
Ex: XPath = “//a[@class= ‘gb_P’ and @data-pid=’23’]”
Using OR expression, any of the condition can be true to identify the element. If both the condition fail then element won’t be determined.
Ex: XPath = “//a[@class= ‘gb_P’ or @data-pid=’23’]”
Starts-with:
The starting portion of the text of the attribute is used to determine the element whose attribute changes dynamically.
Determine ‘Gmail’ element using start-with function
Ex: Xpath=”//a[starts-with(text(),’Gma’)]”
Axes methods:
These methods are used to determine some of the complex, dynamic elements.
Following:
This method selects all the elements in the document of the current node.

Ex: To select all the links after the ‘Selenium Downloads’ using ‘Following’.
XPath = ‘//a[contains(text(),’ Selenium Downloads’)]//following:: a’
Preceding:
Selects all nodes that come before the current node.

Ex: If we need to select ’Selenium Downloads’ using ‘Previous Releases’
XPath = ‘//a[contains(text(),’ Previous Releases’)]//preceding:: a’
Child:
Selects all children elements of the current node.

Ex: To select all the child of ’Selenium Downloads’
XPath = ‘//a[contains(text(),’ Selenium Downloads’)]//child:: a’