XPath Locator in Selenium

 1. What is XPath?

XPath (XML Path Language) is a query language used to navigate through XML (Extensible Markup Language) and HTML documents. It provides a syntax for selecting nodes in an XML document based on their properties, attributes, or position in the document tree.

2. Types of XPath: XPath can be classified into two main types based on how paths are specified:

a. Absolute XPath:

  • Absolute XPath begins with the root node of the XML document and follows the path down to the desired element.
  • It starts with a single forward slash (/) representing the root node and includes the complete path to the element.
  • It is less preferred due to its brittle nature, as any change in the structure of the document can break the XPath.
  • Example: /html/body/div[1]/form/input[2]

b. Relative XPath:

  • Relative XPath starts from any node in the document (not necessarily the root node) and navigates through the document based on the current context.
  • It starts with a double forward slash (//) and allows navigating through the elements relative to the current context.
  • It's more flexible and recommended for automation as it's less likely to break with changes in the document structure.
  • Example: //input[@id='username']

3. Which type of XPath will be preferred in automation? Why? Relative XPath is generally preferred in automation for the following reasons:

  • Flexibility: Relative XPath allows selecting elements based on their attributes or relationships to other elements, making it less dependent on the document's structure.
  • Robustness: Relative XPath is more resistant to changes in the document structure. Even if elements are added or removed, as long as the relative position or attributes of the target element remain unchanged, the XPath will still work.
  • Readability: Relative XPaths are often more concise and easier to understand, as they focus on the specific elements of interest rather than the entire document structure.
  • Maintainability: Since relative XPaths are less likely to break with changes, they require less maintenance effort compared to absolute XPaths.

Examples:

Consider the following HTML snippet for a login form:

<html> <body> <div id="loginForm"> <form> <input type="text" id="username" name="username"> <input type="password" id="password" name="password"> <button type="submit">Login</button> </form> </div> </body> </html>
  • Absolute XPath for the password input field: /html/body/div/form/input[2]

  • Relative XPath for the username input field: //input[@id='username']

In automation, using the relative XPath (//input[@id='username']) would be preferred because it's less dependent on the structure of the document and more resilient to changes. If, for instance, a new div element is added around the form, the relative XPath would still correctly identify the username input field, whereas the absolute XPath might break.

Followers