What Are Absolute And Relative Xpath

Absolute and Relative Xpath

If we write xpath expression from the root node, then it is called Absolute xpath.

Ex :

<html>

<body>

<div>

<a href=”url” />  link 1

<a href=”url” /> link 2

<input type=text id=input a1 />

<input type=text id=input a2 />

</div>

<div>

<input type=text id=input b1 />

<input type=text id=input b2 />

<a href=”url” /> link 3

                   </div>

</body>

</html>

 

2

Ex :

/html/body/div/input  => a1, a2, b1, b2

/html/body/div[1]/input[2]  => a2

/html/body/div/input[1]  =>a1, b1

/html/body/div[2]/a  => link 3

Here we can see that the xpaths are written from the root node and so these are absolute xpaths.

Relative Xpath :

Ex :

//input =>a1, a2, b1, b2

//div/input[1]  => a1,b1

//div[2]/input[2]  => b2

//div[1]/a  => link1, link 2

If you write the xpath in the above format, it is called Relative Xpath. If begins with double slash “//’ which represents search entire web page.

Note 1 :

If we want to narrow down the search, use appropriate tag name after “//”.

Both absolute and relative xpath expressions are written based on the position. Hence, it is called Xpath By Position.

The Disadvantage in Xpath By Position is that the programmer has to remember entire html tree structure as well as the positions of the tags.

If we write xpath expression by position, the expression will be very lengthy. In order to overcome this, we go for Xpath By Attribute.

 General Syntax For Xpath by Attribute :

//tagName[@attribute =/ or // AttributeValue //or /]

Add Comment