Absolute and Relative XPath

Let’s find out about the difference between absolute and relative XPath in this lesson.

What is an absolute and relative XPath?

In an absolute XPath, you traverse from the top of the hierarchy, say html or body node, until the target node in the DOM.

In a relative XPath, as the name suggests, we can start locating the element from anywhere in the hierarchy tree, including the same exact node.

Let’s look at the example below, where the same node is identified using one absolute and multiple relative XPaths:

  • Absolute XPath

     /html/body/div/ul/li[@id='xyz']
    
  • Relative XPath

    //ul/li[@id='xyz']
    

    Or,

     //li[@id='xyz']
    

    Or,

     //*[@id='xyz']
    

All of them will work and identify the same node. Now, let’s understand why we use one over the other while writing XPath expressions.

Which one is better and why?

We should always use relative XPath expressions. Absolute XPath expressions will break if there is any small change in the webpage in the top-level hierarchy nodes w.r.t. to the context node.

Example:

Say a new paragraph described by p in the HTML is introduced before the ul node in the above example. In this case, absolute XPath will fail to locate the node/element, while relative XPath will still continue to work.

The new absolute XPath after the change would be:

  /html/body/div/p/ul/li[@id='xyz']

The addition of the new element won’t impact the relative XPath expression, as it would continue to locate the element on the webpage.

Please Note - The XPath expression starting with // refers to relative XPath, and the expression starting with / refers to absolute XPath, as you can see in the above examples.

Example code

Let’s understand the example code below, which demonstrates the difference between absolute and relative XPath expressions.

  • Webpage: http://codetoautomate.com/xpath-demo-educative/

  • Element: Select ‘apple’ from the fruits dropdown list.

  • Absolute XPath for identifying the above element: /html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[1]/main[1]/article[1]/div[1]/div[1]/div[1]/div[2]/div[2]/p[4]/select[1]/option[@value='apple']

  • Relative XPath for identifying the above element: //option[@value='apple']

  • Have a look at the code below:

Get hands-on with 1200+ tech skills courses.