Saturday, October 6, 2018

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]

No comments:

Post a Comment