what is xpath in Selenium

  • by

What is X Path -:
X Path is a unique path of the element. In any website or web based application contains number of web elements / objects like text field, button, radio button, drop box, link, image etc. This object has unique id or path. If there are common attributes and values then X path is designed to allow the navigation of XML documents with the purpose of selecting individual elements, attributes, or some other part of an XML document for specific processing.

It is used to find the location of any element on a webpage using HTML DOM structure.

It is used mostly to identify exact field among the common attributes and values.

X Paths are derived from the html paths of the objects; it can install firebug, and on the top of firebug install fire path in Mozilla.

At the times X Path generated by Firebug are too complicated and you see there is a possibility of getting a shorter XPath. Based on generated X path it is divided into two types viz.
1] Relative path
2] Absolute path
1] Relative path -:
A relative x path finds the closed id to the DOM element and generates x path starting from that element (middle).

It always starts with ‘double slash’ (/’/’), which means that it can search matching element anywhere form the webpage.

No need to write long path (as start from middle).

A ‘double slash’ (‘//’ ) signifies to look for any child or any grand-child element inside the parent.

Syntax -:
We can write relative x path = //tagname[@attribute=’value’]
// – Is a relative path start from middle or matching element
tagname – Is a Starting name of tag e.g input, div etc.
attribute – Is a name of attribute e.g. id, name, value etc.
value – Is a attribute value e.g. 12, Kumar etc

2] Absolute path -;
It indicates with complete path from the Root Element to the desire element.

It starts with ‘single slash’ (/’’), which means that it can start form root node of the webpage.

Needs to write long path (as starts from root node)

As it is direct way to find the element, but the disadvantage is that if there are any changes made in the path of the element then that x path gets failed.

Syntax -:
We can write relative x path = /html/body/div[2]/div/div
/ – Is a absolute x path starting from root node
body – Element in a body
div – Is a starting node (matching or identify)
[2] – Position of element e.g. [2] indicates 2 number element from div

Which is mostly used among the Relative and Absolute X path -:
It is always better to choose Relative xpath, as it helps us to reduce the chance of element not found exception.
In absolute x path if there are any changes made (webelements when added/Removed) in the path of the element then that x path gets failed

Leave a Reply