What is the difference between relative and absolute XPath in Selenium?


We can have two ways of creating an xpath – relative and absolute. The absolute xpath has the complete path beginning from the root to the element which we want to identify.

An absolute xpath starts with the / symbol. One drawback with the absolute xpath is that if there is any change in attributes beginning from the root to the element, our absolute xpath will become invalid.

The relative xpath starts by referring to the element that we want to identify and not from the root node. A relative xpath starts with the // symbol. It is mainly used for automation since even if an element is removed or added in the DOM, the relative xpath is not impacted.

An absolute xpath is lengthy and difficult to maintain (html/body/tagname/…). While a relative xpath is short (//*[@attribute='value']). Let us identify the Home menu on the below page −

Let us investigate the HTML code of the Home element starting from the root.

The absolute xpath for this element is /html/body/div[1]/div/div[1]/a. It can be verified with the expression $x("/html/body/div[1]/div/div[1]/a") in the browser Console(opens by pressing F12).The image shows the matching element obtained from the absolute xpath expression.

The relative xpath for this element is //a[@title='TutorialsPoint - Home']. It can be verified with the expression $x("//a[@title='TutorialsPoint - Home']") in the browser Console. The image shows the matching element obtained from the relative xpath expression.

Updated on: 08-Nov-2023

22K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements