Absolute and Relative XPath Expressions
Absolute and Relative XPath Expressions
In this tutorial, we will learn about Absolute and Relative XPath Expressions, which are the mechanisms for identifying an element in the document. XPath is a query language used to identify elements in documents. Types of XPath expressions are:
- Absolute XPath Expression
- Relative XPath Expression
Absolute XPath
Absolute XPath starts from the root node and uses a forward slash (/) at the beginning.
An absolute XPath is the complete path from the root node of the document. The absolute path starts with ‘/’
For Example:
/html/body/div/input
Advantages:
- Absolute XPath is fast at identifying elements since it provides a complete path.
Disadvantages:
- If the structure of the webpage changes, such as adding new tags in between, the XPath will break and stop working.
For example:
- If the defined path is:
/html/head/body/table/tbody/tr/th
- But a new tag is added between
body
andtable
, like this:/html/head/body/form/table/tbody/tr/th
- The original XPath will no longer work because the ‘form’ tag has been introduced between
body
andtable
.
Relative XPath
Relative XPath doesn’t require starting from the root node. Instead, it can start from any node of your choice, providing more flexibility. Relative XPath begins with double forward slashes (//
).
Syntax Example: //table/tbody/tr/th
Another example: .//*[@id='username']
Here, the .
at the start indicates that the search begins from the current node. The relative XPath starts with the ‘//’ and searches for the element relative to the current node.
The *
is used to select any element node, and the @id='username'
filters the selection to elements with an id
attribute of username
.
Advantages:
- Relative XPath allows you to specify a shorter path, even starting from the middle of the document. It doesn’t require a full path, making it more flexible.
Disadvantages:
- It may take more time to identify the element because the path is not fully specified.
- If multiple elements match the same relative path, it will select the first element that matches.
XPath Type | Description | Example | Starting Point | Path Depth | Flexibility |
---|---|---|---|---|---|
Absolute XPath ( / ) | Starts from the root node of the document and follows the exact path. | /html/body/div | Starts from the root node. | Follows the complete hierarchical path from the root to the target element. | Less flexible; the path needs to stay the same. |
Relative XPath ( // ) | Can start from any node and search throughout the document, regardless of the depth. | //div | Starts from any node in the document. | Selects elements at any level in the document. | More flexible; can work with partial paths and search anywhere in the document. |