Relative XPath

Introduction

Relative XPath is one of the most commonly used XPath techniques in Selenium. Unlike Absolute XPath, which starts from the root element of the HTML document, Relative XPath begins from anywhere within the HTML structure, making it more flexible, readable, and maintainable.

Relative XPath is widely used in Selenium automation because it is less sensitive to minor changes in the webpage structure and provides multiple ways to locate web elements using attributes, text values, and relationships between elements.

In this tutorial, you’ll learn what Relative XPath is, why it is used, its syntax, practical examples, real-world use cases, common mistakes, and best practices.


What is Relative XPath?

Relative XPath is an XPath expression that starts with // and searches for matching elements anywhere within the HTML document.

Unlike Absolute XPath, it does not depend upon the complete HTML hierarchy, making it significantly more reliable for automation projects.

For example, consider the following HTML:

<form>
    <input
        id="username"
        type="text">

    <input
        name="password"
        type="password">
</form>

The Username textbox can be located using:

//input[@id='username']

and the Password textbox can be located using:

//input[@name='password']

Relative XPath searches for matching elements anywhere within the webpage without requiring the complete HTML path.


Why Use Relative XPath?

Relative XPath is useful because it:

  • Produces shorter and more readable locators.

  • Is less sensitive to UI changes.

  • Supports locating dynamic web elements.

  • Can identify elements using attributes and text values.

  • Improves framework maintainability.

  • Is widely used in modern Selenium automation frameworks.


Syntax

driver.find_element(
    By.XPATH,
    "//tagname[@attribute='value']"
)

Where:

  • By.XPATH → Locator Strategy.

  • // → Searches anywhere within the HTML document.

  • tagname → HTML tag of the required element.

  • attribute='value' → Attribute used to identify the element.


Example

The Login page contains Username and Password textboxes that can be located using Relative XPath expressions.

The Selenium code is:

from selenium import webdriver
from selenium.webdriver.common.by import By


# Topic: 13. XPath - Relative XPath
# Practice site: https://the-internet.herokuapp.com/login
# Run: pytest -s 13_examples/test_03_relative_xpath.py
#
# Relative XPath starts with // and searches anywhere in the document, making
# it more flexible than absolute XPath.


def test_relative_xpath():
    driver = webdriver.Chrome()

    try:
        driver.get("https://the-internet.herokuapp.com/login")

        username = driver.find_element(
            By.XPATH,
            "//input[@id='username']"
        )

        password = driver.find_element(
            By.XPATH,
            "//input[@name='password']"
        )

        assert username.is_displayed()
        assert password.is_displayed()

    finally:
        driver.quit()

Output

The Username and Password
textboxes are located
successfully using Relative
XPath expressions.

Understanding the Code

Import the By Class

from selenium.webdriver.common.by import By

Imports Selenium’s locator strategies.

Open the Login Page

driver.get(
    "https://the-internet.herokuapp.com/login"
)

Launches the Selenium practice website.

Locate the Username Textbox

driver.find_element(
    By.XPATH,
    "//input[@id='username']"
)

Locates the Username textbox using its unique id attribute.

Locate the Password Textbox

driver.find_element(
    By.XPATH,
    "//input[@name='password']"
)

Locates the Password textbox using its name attribute.

Validate the Elements

assert username.is_displayed()
assert password.is_displayed()

Verifies that both textboxes are present and visible on the webpage.


How Relative XPath Works

        Python Script
               │
               ▼
            By.XPATH
               │
               ▼
      Read XPath Expression
               │
               ▼
       Search HTML Document
               │
               ▼
      Locate Matching Element
               │
               ▼
         Perform Validation

Practical Example

Suppose you’re automating a Login page.

The Username and Password fields contain stable HTML attributes that uniquely identify them.

Selenium uses:

//input[@id='username']

//input[@name='password']

to locate both textboxes without depending upon the complete HTML hierarchy.

This makes the automation script more reliable and easier to maintain.


Automation Testing Example

Consider an online banking application.

The Login page contains Username and Password fields whose positions may change after minor UI modifications.

Instead of using Absolute XPath expressions, Selenium uses Relative XPath to identify the required elements using their stable attributes, significantly improving framework maintainability during regression testing.


Real-World Example

Relative XPath is widely used in automation projects involving:

  • Banking applications.

  • E-Commerce websites.

  • Healthcare portals.

  • CRM systems.

  • ERP applications.

  • Government websites.

  • SaaS products.

  • Enterprise web applications.

Automation engineers frequently use Relative XPath whenever simpler locator strategies are unavailable or when flexible element identification is required.


Advantages of Relative XPath

  • Short and readable.

  • Less sensitive to HTML structure changes.

  • Supports locating dynamic web elements.

  • Easy to maintain.

  • Highly flexible.

  • Widely used in professional automation frameworks.


Limitations of Relative XPath

  • Poorly written XPath expressions may return multiple matching elements.

  • Dynamic attributes can affect locator reliability.

  • Complex XPath expressions may reduce readability.

  • Incorrect attribute selection can make automation scripts unstable.


Common Mistakes Beginners Make

Writing Overly Complex XPath Expressions

Avoid

/html/body/div/div/form/div/input

Prefer

//input[@id='username']

Shorter XPath expressions are easier to maintain and understand.

Using Dynamic Attributes

Avoid locating elements using dynamically generated IDs or classes whenever possible.

Ignoring Simpler Locator Strategies

Before using Relative XPath, always check whether simpler locator strategies such as ID, Name, or CSS Selectors can uniquely identify the required element.


Best Practices

  • Prefer Relative XPath over Absolute XPath whenever possible.

  • Keep XPath expressions short and readable.

  • Use stable and unique HTML attributes.

  • Avoid depending upon deeply nested HTML structures.

  • Verify XPath expressions using browser Developer Tools.

  • Write maintainable and reusable XPath locators within automation frameworks.

  • Prefer simpler locator strategies whenever appropriate.


Conclusion

Relative XPath is one of the most powerful and widely used locator strategies in Selenium automation. It provides flexible, readable, and maintainable XPath expressions that are less sensitive to webpage structure changes when compared with Absolute XPath.

Understanding Relative XPath provides an excellent foundation for learning Dynamic XPath, XPath Functions, and XPath Axes used extensively in modern Selenium automation frameworks.


Frequently Asked Questions (FAQs)

What is Relative XPath?

Relative XPath is an XPath expression that starts with // and searches for matching elements anywhere within the HTML document.

What is the syntax for Relative XPath?

driver.find_element(
    By.XPATH,
    "//tagname[@attribute='value']"
)

Why is Relative XPath preferred over Absolute XPath?

Because it is shorter, easier to maintain, and less sensitive to changes in the HTML hierarchy.

Can Relative XPath locate dynamic web elements?

Yes.

Relative XPath provides multiple techniques for locating dynamic web elements using attributes, text values, and XPath functions.

When should I use Relative XPath?

Use Relative XPath whenever flexible and maintainable element identification is required or when simpler locator strategies are insufficient.


Key Takeaways

  • Relative XPath begins with // and searches anywhere within the HTML document.

  • It is shorter, more flexible, and easier to maintain than Absolute XPath.

  • Relative XPath is widely used in professional Selenium automation frameworks.

  • Prefer stable HTML attributes when writing XPath expressions.

  • Keep XPath expressions simple, readable, and maintainable.

  • Relative XPath provides the foundation for learning Dynamic XPath, XPath Functions, and XPath Axes.