Choosing the Right Locator

Introduction

One of the most important skills in Selenium automation is selecting the right locator for identifying web elements. A good locator makes your automation scripts stable, reliable, and easy to maintain, while a poor locator often leads to flaky tests that fail whenever the application’s UI changes.

Selenium provides several locator strategies such as ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, CSS Selector, and XPath. However, not all locators are equally reliable. Choosing the most stable locator is considered a best practice in automation testing.

In this tutorial, you will learn how to choose the right locator, the recommended order of preference, practical examples, real-world applications, common mistakes, best practices, and frequently asked interview questions.


What is a Good Locator?

A good locator is one that uniquely identifies a web element and remains stable even when the application’s UI changes.

A good locator should be:

  • Unique

  • Stable

  • Easy to understand

  • Easy to maintain

  • Independent of UI layout changes


Why is Choosing the Right Locator Important?

Choosing the right locator helps to:

  • Reduce test failures.

  • Improve automation stability.

  • Make scripts easier to maintain.

  • Speed up element identification.

  • Reduce maintenance effort when the UI changes.

Poor locators often break after small UI modifications, causing unnecessary test failures.


Recommended Locator Priority

When multiple locator options are available, the following order is generally recommended:

  1. ID

  2. Name

  3. CSS Selector

  4. XPath

  5. Link Text / Partial Link Text

  6. Class Name

  7. Tag Name

Whenever possible, prefer ID because it is usually unique and specifically designed to identify an element.


Characteristics of a Good Locator

A good locator should:

  • Identify only one element.

  • Be less likely to change frequently.

  • Avoid unnecessary complexity.

  • Not depend on the page layout.

  • Be easy for other automation engineers to understand.


Practical Example

The following example demonstrates how to choose stable locators for identifying web elements.

The automation script opens the Selenium practice login page, locates the username field using its ID, locates the Login button using a CSS Selector, and verifies both elements.

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


# Topic: 10. Understanding Selenium Locators - Choosing the Right Locator
# Practice site: https://the-internet.herokuapp.com/login
#
# Prefer stable, unique locators. ID is the most reliable when available
# because it is designed to uniquely identify an element.


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

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

        username_field = driver.find_element(By.ID, "username")
        login_button = driver.find_element(By.CSS_SELECTOR, "button[type='submit']")

        assert username_field.get_attribute("id") == "username"
        assert login_button.text == "Login"

    finally:
        driver.quit()

Output

Browser launched successfully.

Login page opened successfully.

Username field located using ID.

Login button located using CSS Selector.

Assertions Passed.

Test Executed Successfully.

Understanding the Code

Import Required Modules

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

Imports the Selenium WebDriver module and the By class used for locating web elements.


Launch Chrome Browser

driver = webdriver.Chrome()

Creates a new Chrome browser session.


Open the Login Page

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

Navigates to the Selenium practice login page.


Locate the Username Field

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

Uses the ID locator, which is the most reliable choice because IDs are generally unique within a webpage.


Locate the Login Button

login_button = driver.find_element(
    By.CSS_SELECTOR,
    "button[type='submit']"
)

Uses a CSS Selector to identify the Login button based on its type attribute.


Validate the Located Elements

assert username_field.get_attribute("id") == "username"

assert login_button.text == "Login"

Verifies that:

  • The username field has the expected ID.

  • The Login button displays the correct text.


Close the Browser

driver.quit()

Closes all browser windows and ends the WebDriver session.


Locator Selection Flow

Inspect the Element
        │
        ▼
Is a Unique ID Available?
        │
      Yes
        │
        ▼
Use ID Locator
        │
      No
        │
        ▼
Check Name Attribute
        │
      No
        │
        ▼
Use CSS Selector
        │
      If Needed
        │
        ▼
Use XPath
        │
        ▼
Avoid Weak Locators

Automation Testing Example

Suppose you’re automating the login page of an online shopping application.

Instead of locating the username field using a long XPath like:

driver.find_element(
    By.XPATH,
    "/html/body/div/form/input[1]"
)

Use the stable ID:

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

This makes the automation script much easier to read and maintain.


Real-World Example

Consider an online banking application.

The Login button has the following HTML:

<button type="submit">
    Login
</button>

A reliable CSS Selector would be:

driver.find_element(
    By.CSS_SELECTOR,
    "button[type='submit']"
)

This locator is cleaner and more maintainable than using a lengthy absolute XPath.


Common Mistakes Beginners Make

Using Absolute XPath

Incorrect

driver.find_element(
    By.XPATH,
    "/html/body/div[2]/div/form/input"
)

Absolute XPaths are fragile because even small UI changes can break them.


Better

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

Prefer stable locators whenever possible.


Using Class Name When Multiple Elements Share the Same Class

Incorrect

driver.find_element(By.CLASS_NAME, "button")

Multiple elements may use the same class, leading to incorrect element selection.


Choosing Complex XPath Unnecessarily

Incorrect

driver.find_element(
    By.XPATH,
    "//div[@class='container']/form/div/input"
)

If an ID is available, use it instead.


Best Practices

  • Prefer ID whenever available.

  • Use Name if ID is not present.

  • Use CSS Selectors before XPath whenever possible.

  • Write short and readable locators.

  • Avoid absolute XPath.

  • Avoid locating elements using dynamically generated attributes.

  • Always verify that the locator uniquely identifies one element.


Conclusion

Choosing the right locator is one of the most important aspects of Selenium automation. Stable locators reduce maintenance, improve test reliability, and make automation frameworks easier to understand.

Whenever possible, prefer ID, followed by Name, CSS Selector, and finally XPath. Following these best practices will help you build robust and maintainable Selenium automation scripts.


Frequently Asked Questions (FAQs)

Which locator is the most reliable?

The ID locator is generally the most reliable because IDs are designed to uniquely identify elements.


Should I always use XPath?

No.

Use XPath only when simpler locators such as ID, Name, or CSS Selector are not available.


Why are CSS Selectors often preferred over XPath?

CSS Selectors are usually shorter, easier to read, and often perform better than complex XPath expressions.


Why should I avoid absolute XPath?

Absolute XPaths depend on the page structure and break easily when the UI changes.


What should I do if no stable locator is available?

Use a well-designed relative XPath or CSS Selector that relies on stable attributes.


Key Takeaways

  • Choosing the right locator improves automation stability and reduces maintenance.

  • Prefer locators in this order: ID → Name → CSS Selector → XPath.

  • A good locator should be unique, stable, and easy to maintain.

  • Avoid absolute XPath whenever possible.

  • Prefer simple and readable locators over complex expressions.

  • Always verify that the locator uniquely identifies the intended element.

  • Choosing the right locator is a fundamental Selenium automation and interview skill.