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

SeleniumAutomation TestingTesting Tools

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.

Published on 06-Apr-2021 11:19:09