Friday, October 5, 2018

Types of XPath

XPath can be created in two ways:

  1. Absolute XPath
  2. Relative XPath
Types of XPath in Selenium WebDriver

Absolute XPath

The easiest way of finding the XPath is to use the Browser Inspector tool to locate an element and get the XPath of it.

Absolute XPath in Selenium WebDriver

Absolute XPath begins with the root of the HTML pages and is prefixed with a ' / '.

For example:
/html/body/div[1]/div[2]/div[1]/form/div[1]/div/div[1]/div/div/input[1]

Pros

  • It is the easiest way to locate an element.
  • It identifies the element very fast

Cons

  • It is not readable as it can be very lengthy
  • It is very delicate as a minor structural change can make it useless.
Let's discuss the second con of Absolute XPath below:

<html>
   <body>
      <table>
         <tr>
            <th>Column One</th>
            <th>Column Two</th>
         </tr>
      </table>
   </body>
</html>

For the above HTML document if user wants to get the second 'th' then the Absolute XPath will be
/html/body/table/tr/th[2]
Now if we add a new tag between the body and table as below:

<html>
   <body>
      <p>Paragraph One</p>
      <table>
         <tr>
            <th>Column One</th>
            <th>Column Two</th>
         </tr>
      </table>
   </body>
</html>

then the first path will not work as 'p' tag is added in between the body and table. In this case, we have to rewrite the XPath as below:
/html/body/p/table/tr/th[2]

Relative XPath

A Relative XPath is the path which starts from the node of our choice and is prefixed with a ' // '. It doesn't need to start from the root node.

For example:
//span[@class = 'Email']

Pros

  • It starts from the node of our choice
  • It is readable and shorter than Absolute XPath
  • It works even after structural change

Cons

  • It takes more time to identify element as we specify the partial path
  • If there are multiple elements for the same path, it will select the first element that is identified
Let's take a look at a Relative XPath below:
//li[@id = 'ogbkddg:4']
Relative XPath in Selenium WebDriver

Here, //li[@id = 'ogbkddg:4'] is a Relative XPath and as we can see it did not start from the root node and started from the node of our choice. It is also short and very easy to read. Even if there is any kind of structural change, it will work just fine.

No comments:

Post a Comment