XPath can be created in two ways:
- Absolute XPath
- Relative XPath
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 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.
<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
//li[@id = 'ogbkddg:4']
No comments:
Post a Comment