Locator Best Practices

Introduction

One of the most important factors in creating reliable Selenium automation scripts is choosing the right locator strategy. A poorly chosen locator can cause test failures even when the application’s functionality is working correctly.

Locator Best Practices are guidelines for selecting stable, unique, and maintainable locators that make automation scripts less prone to failure. Instead of relying on fragile locators such as absolute XPath, automation engineers should prefer attributes like ID, Name, or well-structured CSS Selectors.

Following these best practices results in faster, more reliable, and easier-to-maintain Selenium test scripts.

In this tutorial, you’ll learn the best practices for locating web elements and understand why choosing the right locator is essential for automation testing.


What are Locator Best Practices?

Locator Best Practices are recommendations for identifying web elements in a reliable and maintainable way.

The goal is to:

  • Locate elements quickly.

  • Reduce flaky tests.

  • Minimize maintenance.

  • Improve test execution speed.

  • Increase automation reliability.

Choosing the right locator strategy is one of the first steps toward building a stable Selenium framework.


Why Follow Locator Best Practices?

Using good locators provides several benefits:

  • Improves test stability.

  • Reduces maintenance effort.

  • Speeds up test execution.

  • Minimizes test failures caused by UI changes.

  • Makes automation scripts easier to read.

  • Creates reliable and scalable automation frameworks.


Recommended Locator Priority

PriorityLocatorRecommendation
1IDBest choice (unique and fastest)
2NameVery reliable if unique
3CSS SelectorFast and flexible
4XPath (Relative)Use when other locators are unavailable
5XPath (Absolute)Avoid whenever possible

Example

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


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

    try:
        driver.get("https://www.testmuai.com/selenium-playground/simple-form-demo")

        # Good: ID locator (fast and stable)
        message_input = driver.find_element(By.ID, "user-message")

        # Good: CSS selector tied to a stable structure
        show_button = driver.find_element(By.CSS_SELECTOR, "#showInput")

        message_input.send_keys("Locator Best Practices")
        show_button.click()

        assert driver.find_element(By.ID, "message").text == "Locator Best Practices"
    finally:
        driver.quit()

Understanding the Code

Import Required Modules

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

The webdriver module is imported to launch and control the browser.

The By class is imported to locate web elements using different locator strategies such as ID, NAME, CSS_SELECTOR, and XPATH.


Create the Test Function

def test_locator_best_practices():

A test function is created following PyTest naming conventions. Since the function name starts with test_, PyTest will automatically discover and execute it.


Launch the Browser

driver = webdriver.Chrome()

A new Chrome browser session is created.


Use a try-finally Block

try:

The test logic is placed inside a try block.

This ensures that the browser will always be closed using the finally block, even if the test fails.


Open the Webpage

driver.get("https://www.testmuai.com/selenium-playground/simple-form-demo")

The browser navigates to the Selenium Playground Simple Form Demo page.


Locate the Input Field Using ID

message_input = driver.find_element(By.ID, "user-message")

The message input field is located using its unique ID.

Using ID is considered the best practice because it is:

  • Fast

  • Unique

  • Stable

  • Easy to maintain


Locate the Button Using CSS Selector

show_button = driver.find_element(By.CSS_SELECTOR, "#showInput")

The Show Message button is located using a CSS Selector.

CSS Selector is generally faster than XPath and is preferred when a suitable ID is not available.


Enter the Message

message_input.send_keys("Locator Best Practices")

The text “Locator Best Practices” is entered into the message input field.


Click the Button

show_button.click()

The Show Message button is clicked to display the entered message.


Verify the Result

assert driver.find_element(By.ID, "message").text == "Locator Best Practices"

The script locates the output element using its ID and verifies that the displayed message matches the expected text.


Close the Browser

finally:
    driver.quit()

The browser is closed after the test completes.

Using driver.quit() inside the finally block ensures proper cleanup of browser resources.


Good vs Poor Locator Choices

Good PracticePoor Practice
By.IDAbsolute XPath
By.NAMEXPath based on indexes
By.CSS_SELECTORDynamic IDs that change every run
Relative XPathVery long XPath expressions

Why Avoid Absolute XPath?

Poor Example

/html/body/div[2]/div/div/form/input

This locator depends on the exact structure of the HTML page.

If even a small change is made to the page structure, the XPath may become invalid and the test will fail.


Better Examples

driver.find_element(By.ID, "user-message")

or

driver.find_element(By.CSS_SELECTOR, "#showInput")

These locators are shorter, easier to understand, and much more reliable.


Practical Example

Suppose an e-commerce website adds a new <div> element to its product page.

Automation scripts using absolute XPath may stop working because the HTML structure has changed. However, scripts using stable locators like ID or CSS Selector continue to work without any modifications.


Automation Testing Example

Consider a login page.

Instead of locating the username field using a long XPath, the automation engineer uses:

driver.find_element(By.ID, "username")

Even if the page layout changes, the automation script continues to work as long as the ID remains unchanged.


Real-World Example

Locator best practices are followed in:

  • Banking applications

  • Healthcare systems

  • E-commerce platforms

  • CRM applications

  • ERP systems

  • Government portals

  • SaaS products

  • Enterprise Selenium automation frameworks


Advantages of Following Locator Best Practices

  • Improves automation stability.

  • Reduces flaky tests.

  • Speeds up test execution.

  • Simplifies maintenance.

  • Makes scripts easier to read.

  • Reduces failures caused by UI changes.

  • Produces reliable automation frameworks.


Common Mistakes Beginners Make

Using Absolute XPath

Avoid locators like:

/html/body/div[2]/div/div/form/input

These locators are fragile and break when the page structure changes.


Choosing Dynamic Attributes

Avoid using dynamic ID or class attributes that change every time the application loads.


Writing Long XPath or CSS Selectors

Keep locators short, readable, and easy to maintain.


Ignoring Unique Attributes

Always check whether an element has a unique ID or Name before using XPath.


Copying Browser-Generated XPath

Browser-generated XPath expressions are often long and difficult to maintain.

Review and simplify them before adding them to your automation framework.


Best Practices

  • Prefer ID whenever it is available.

  • Use Name if it uniquely identifies the element.

  • Use CSS Selector when ID is unavailable.

  • Use Relative XPath only when necessary.

  • Avoid Absolute XPath whenever possible.

  • Keep locators short, readable, and stable.

  • Store reusable locators in a centralized location such as a Page Object or Object Repository.

  • Avoid relying on dynamic attributes that may change between executions.


Conclusion

Locator Best Practices are essential for building stable and maintainable Selenium automation frameworks. Choosing reliable locators such as ID and CSS Selector, while avoiding fragile absolute XPath expressions, significantly improves the reliability of automation scripts. Following these practices reduces maintenance effort, minimizes flaky tests, and helps create professional-quality automation frameworks.


Frequently Asked Questions (FAQs)

What is the best locator in Selenium?

ID is generally the best locator because it is unique, fast, and reliable.


Why is CSS Selector preferred over XPath?

CSS Selector is usually faster, easier to read, and simpler to maintain than complex XPath expressions.


Why should Absolute XPath be avoided?

Absolute XPath depends on the exact HTML structure. Even small changes to the page layout can break the locator.


When should Relative XPath be used?

Relative XPath should be used only when stable locators such as ID, Name, or CSS Selector are not available.


Where should locators be stored in a framework?

Reusable locators should be stored in a centralized location, such as a Page Object or Object Repository, making maintenance easier.


Key Takeaways

  • ID is the preferred locator because it is unique, fast, and stable.

  • Use Name when it uniquely identifies an element.

  • Use CSS Selector when ID is unavailable.

  • Use Relative XPath only when necessary.

  • Avoid Absolute XPath because it is fragile and difficult to maintain.

  • Keep locators short, readable, and stable.

  • Store reusable locators in a centralized location for easier framework maintenance.