Introduction
Writing a Relative Locator that works is easy, but writing one that is reliable, maintainable, and resistant to UI changes is what separates a beginner from a professional automation engineer.
Although Selenium 4 Relative Locators provide powerful position-based element identification techniques, they should be used thoughtfully. In many situations, traditional locator strategies such as ID, Name, CSS Selectors, and XPath are simpler, faster, and more maintainable.
Relative Locators are most useful when web elements do not have unique attributes but maintain stable visual relationships with other elements on the webpage.
In this tutorial, you’ll learn the best practices for using Relative Locators, practical examples, common mistakes, and recommendations followed in real-world automation projects.
Why Follow Relative Locator Best Practices?
Following best practices helps you:
Improve automation reliability.
Reduce script maintenance.
Create readable locators.
Improve framework scalability.
Reduce automation failures caused by UI changes.
Choose the most appropriate locator strategy for every scenario.
Best Practice 1: Prefer Unique Attributes Whenever Available
Always prefer traditional locator strategies such as:
By.ID
By.NAME
By.CSS_SELECTOR
or
By.XPATH
before using Relative Locators.
Good
driver.find_element(
By.ID,
"username"
)
Avoid
driver.find_element(
locate_with(
By.TAG_NAME,
"input"
).above(password_field)
)
when a stable and unique ID already exists.
Traditional locator strategies are usually simpler and easier to maintain.
Best Practice 2: Use Relative Locators Only When Necessary
Relative Locators should be used when:
Elements do not contain unique IDs.
HTML attributes change frequently.
Visual relationships remain stable.
Traditional locators become difficult to maintain.
Examples include:
Registration forms.
Payment pages.
Dynamic dashboards.
Modern UI frameworks.
Best Practice 3: Use Stable Reference Elements
Always choose reference elements that are unlikely to change.
Good
password_field = driver.find_element(
By.ID,
"password"
)
Avoid
temporary_button = driver.find_element(
By.CSS_SELECTOR,
".dynamic-class"
)
Using stable reference elements significantly improves locator reliability.
Best Practice 4: Keep Relative Locators Simple
Avoid unnecessarily complex locator combinations.
Good
locate_with(
By.TAG_NAME,
"input"
).above(password_field)
Avoid
locate_with(
By.TAG_NAME,
"input"
).above(password_field).near(
login_button
)
Simple locators are easier to understand and maintain.
Best Practice 5: Verify Visual Relationships
Before using Relative Locators, verify that elements consistently maintain their visual positions across:
Browsers.
Screen resolutions.
Responsive layouts.
Test environments.
If visual relationships change frequently, traditional locator strategies may be more reliable.
Best Practice 6: Use Relative Locators as a Fallback Strategy
Professional automation frameworks usually follow the following order:
ID
│
▼
Name
│
▼
CSS Selector
│
▼
XPath
│
▼
Relative Locator
│
▼
Use When Needed
Relative Locators should complement traditional locator strategies rather than replace them.
Example
The Login page contains Username and Password textboxes. The Username field has a stable ID attribute and can be located directly. Selenium also demonstrates how the same element can be identified using a Relative Locator when visual positioning becomes important.
The Selenium code is:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.relative_locator import locate_with
# Topic: 14. Selenium 4 Relative Locators - Relative Locator Best Practices
# Practice site: https://the-internet.herokuapp.com/login
# Run: pytest -s 14_examples/test_06_relative_locator_best_practices.py
#
# Use relative locators when elements lack unique IDs but have a stable visual
# relationship. Prefer ID or CSS when those are available.
def test_relative_locator_best_practices():
driver = webdriver.Chrome()
try:
driver.get("https://the-internet.herokuapp.com/login")
# Best practice: use ID when available
username_by_id = driver.find_element(
By.ID,
"username"
)
# Relative locator as fallback when visual position is the anchor
password_field = driver.find_element(
By.ID,
"password"
)
username_by_relative = driver.find_element(
locate_with(
By.TAG_NAME,
"input"
).above(password_field)
)
assert username_by_id.get_attribute(
"id"
) == "username"
assert username_by_relative.get_attribute(
"id"
) == "username"
finally:
driver.quit()
Output
The Username textbox is
located successfully using
both the ID locator and the
above() Relative Locator.
Understanding the Code
Import the Required Classes
from selenium.webdriver.common.by import By
from selenium.webdriver.support.relative_locator import (
locate_with
)
Imports Selenium’s locator strategies and Relative Locator functionality.
Open the Login Page
driver.get(
"https://the-internet.herokuapp.com/login"
)
Launches the Selenium practice website.
Locate the Username Field Using ID
driver.find_element(
By.ID,
"username"
)
Uses the most reliable locator strategy available for the Username textbox.
Locate the Password Field
driver.find_element(
By.ID,
"password"
)
Locates the Password textbox that will serve as the reference element.
Locate the Username Field Using a Relative Locator
driver.find_element(
locate_with(
By.TAG_NAME,
"input"
).above(password_field)
)
Uses the above() Relative Locator as an alternative approach based on visual positioning.
Validate the Elements
assert username_by_id.get_attribute(
"id"
) == "username"
assert username_by_relative.get_attribute(
"id"
) == "username"
Verifies that both locator strategies successfully identify the same element.
How Relative Locator Best Practices Work
Python Script
│
▼
Check for Unique Attributes
│
▼
ID Available?
/ \
Yes No
│ │
▼ ▼
Use ID Use Relative
Locator
│
▼
Locate Reference Element
│
▼
Apply Relative Locator
│
▼
Validate Element
Practical Example
Suppose you’re automating a Registration page.
The Email textbox contains a stable ID attribute, while the Confirm Email field does not contain any unique attributes but always appears below the Email textbox.
Selenium can use:
By.ID
for the Email field and:
below()
for the Confirm Email field.
This approach produces reliable and maintainable automation scripts.
Automation Testing Example
Consider an online banking application.
During UI enhancements, developers frequently modify CSS classes and HTML attributes while preserving the visual layout of the webpage.
Professional automation frameworks use traditional locator strategies whenever possible and reserve Relative Locators for situations where visual relationships provide better locator stability.
This significantly reduces framework maintenance during regression testing.
Real-World Example
Automation engineers frequently follow Relative Locator best practices while working with:
Banking applications.
E-Commerce websites.
Healthcare portals.
CRM systems.
ERP applications.
SaaS products.
Enterprise web applications.
Registration forms.
Dynamic dashboards.
Choosing the most appropriate locator strategy significantly improves automation reliability across large projects.
Advantages of Following Best Practices
Improves locator reliability.
Reduces maintenance effort.
Produces cleaner automation scripts.
Improves framework scalability.
Reduces automation failures caused by UI changes.
Improves code readability.
Common Mistakes Beginners Make
Using Relative Locators Everywhere
Avoid
locate_with(
By.TAG_NAME,
"input"
).above(password_field)
for every element on the webpage.
Prefer
driver.find_element(
By.ID,
"username"
)
whenever a unique ID is available.
Ignoring Stable Locator Strategies
Always prefer:
ID
Name
CSS Selectors
XPath
before using Relative Locators.
Using Dynamic Reference Elements
Avoid using reference elements whose positions or attributes frequently change.
Best Practices Summary
Prefer ID whenever available.
Use Relative Locators only when necessary.
Choose stable reference elements.
Keep Relative Locators simple and readable.
Verify visual relationships across environments.
Use Relative Locators as a fallback strategy.
Write reusable locators within automation frameworks.
Conclusion
Relative Locators introduced in Selenium 4 provide powerful position-based element identification techniques. However, they should complement—not replace—traditional locator strategies. Professional automation frameworks prioritize simple and stable locators whenever possible and use Relative Locators only when visual relationships provide the most reliable solution.
Following Relative Locator best practices significantly improves framework maintainability, readability, and long-term automation reliability.
Frequently Asked Questions (FAQs)
Should I always use Relative Locators?
No.
Prefer traditional locator strategies such as ID, Name, CSS Selectors, and XPath whenever they uniquely identify an element.
When should I use Relative Locators?
Use Relative Locators when:
Unique attributes are unavailable.
Visual relationships are stable.
Traditional locators are difficult to maintain.
Which locator strategy should I prefer?
Professional automation frameworks generally follow this order:
ID
Name
CSS Selector
XPath
Relative Locator (when necessary)
Can Relative Locators improve framework maintainability?
Yes.
When used appropriately, Relative Locators significantly improve locator flexibility while reducing automation failures caused by changing HTML attributes.
Are Relative Locators useful for modern web applications?
Yes.
They are particularly useful when working with dynamic and component-based web applications that maintain stable visual layouts.
Key Takeaways
Prefer traditional locator strategies whenever possible.
Use Relative Locators only when visual relationships improve locator reliability.
Choose stable reference elements.
Keep Relative Locators simple and maintainable.
Verify element positioning across browsers and environments.
Relative Locators should complement—not replace—other Selenium locator strategies.
Following best practices significantly improves framework scalability and automation reliability.
