Contents

    Guides

    What Are Locators in Selenium and How to Use Them

    Published on

    September 22, 2025
    What Are Locators in Selenium and How to Use Them

    Automating web applications can quickly become frustrating when tests fail due to elements not being found or misidentified. Hard-coded paths, changing attributes, or dynamic pages can make scripts unreliable and maintenance-heavy.

    Locators in Selenium address this challenge by providing a reliable method to identify and interact with elements such as buttons, text fields, links, and images. Using locators effectively reduces test failures and ensures scripts remain maintainable even as the application evolves. 

    This article explains what locators are, how they work, different types of locators, and best practices for selecting and using them in automation scripts.

    What Are Locators in Selenium

    Locators in Selenium are strategies used to find and interact with elements on a web page. Without locators, Selenium cannot identify which element to click, type into, or verify. Web applications often contain numerous elements with similar characteristics, and many of them can change dynamically, making accurate identification challenging.

    Locators provide a systematic way to pinpoint these elements reliably. They are the bridge between the automation script and the web page, ensuring that actions like entering text, clicking buttons, or retrieving information are performed on the correct elements. Below are the main aspects that define locators in Selenium:

    • Identification Method: Locators define how Selenium identifies an element, whether by ID, class, name, XPath, or other attributes.
    • Uniqueness: A good locator points to a single element or a predictable set of elements, preventing script errors.
    • Maintainability: Well-chosen locators reduce the need to frequently update test scripts when the UI changes.

    Why Use Locators in Selenium

    Automation scripts often fail when elements are misidentified or located incorrectly. Pages frequently contain dynamic content, repeated element structures, or changing attributes. 

    Here is why using locators is critical for effective automation:

    • Precision Targeting: Locators allow Selenium to interact with the exact element even on pages with multiple similar components. For example, finding a login button among several buttons with the same class name is possible using ID or XPath locators.
    • Dynamic Content Handling: Modern web applications often generate elements dynamically. Using locators like CSS selectors or XPath with conditions enables scripts to handle elements that load asynchronously or change attributes at runtime.
    • Reduced Maintenance: Strong locators reduce the need for constant script updates. Scripts that rely on stable attributes like IDs or well-structured XPath expressions remain functional even after minor UI changes.
    • Cross-Browser Consistency: Some browsers render elements differently or introduce subtle DOM changes. Locators allow Selenium to abstract these differences and interact consistently across Chrome, Firefox, Edge, and others.
    • Optimized Performance: Efficient locators minimize DOM traversal time. For instance, locating by ID is faster than iterating through complex XPath queries, which matters when running large test suites frequently.

    How Locators Work in Selenium

    When a Selenium script interacts with a web element, it relies on locators to find that element in the DOM. The process involves searching, matching, and executing actions. Here is how it works step by step:

    1. Locator Definition: The script specifies a locator, such as an ID, class, XPath, or CSS selector, to identify the element. This tells Selenium exactly what attribute or path to look for.
    2. DOM Search: Selenium communicates with the browser to traverse the DOM and find elements matching the locator criteria. For dynamically loaded content, Selenium ensures the page has fully rendered before attempting to locate elements.
    3. Element Matching: The browser evaluates the locator. findElement() returns the first matching element, whereas findElements() returns all matching elements. If no match is found, Selenium throws a NoSuchElementException.
    4. Reference Storage: Once found, Selenium stores a reference to the element object in memory. This allows subsequent actions, such as clicking or sending keys. If the DOM changes, this reference may become stale, leading to a StaleElementReferenceException.
    5. Action Execution: Selenium performs the requested action on the located element, like clicking, typing, or retrieving text. The precision of this step depends on the correctness of the locator.
    6. Error Handling: If the element is not interactable due to visibility, overlapping elements, or stale references, Selenium reports an exception. Testers can combine locators with waits to ensure elements are ready for interaction.

    Types of Selenium Locators and How to Use Them

    Selenium provides multiple ways to locate elements on a web page. Each locator works differently depending on the HTML structure and available attributes. Using the right locator ensures scripts are reliable, maintainable, and adaptable to changes.

    1. Locating Elements by ID

    ID locators in Selenium use the id attribute of an element, which is usually unique on a web page. This makes it the most straightforward and reliable way to find a specific element. By targeting the ID, Selenium can quickly identify the element without scanning the entire DOM, making scripts faster and more stable.

    For example, to enter text into a username field and click a button:

    WebElement usernameField = driver.findElement(By.id("username"));

    usernameField.sendKeys("testUser");

    WebElement loginButton = driver.findElement(By.id("loginBtn"));

    loginButton.click();

    Because IDs are unique, this method ensures that actions are performed on the intended element, even on pages with multiple similar elements. It is particularly effective when IDs are static and not dynamically generated.

    2. Locating Elements by Class Name

    Class name locators find elements that share a CSS class. This is useful when multiple elements belong to the same functional group, such as buttons, input fields, or labels.

    For example, to interact with a single element using its class name:

    WebElement button = driver.findElement(By.className("submit-button"));

    button.click();

    When several elements share the same class, you can retrieve all of them using findElements():

    List<WebElement> buttons = driver.findElements(By.className("submit-button"));

    buttons.get(1).click(); // clicks the second button

    3. Locating Elements by Name

    The name attribute is commonly used for form elements like text inputs, radio buttons, and checkboxes. Selenium can locate elements by matching the name attribute exactly.

    For example, to enter a value in a text field or select a radio button:

    WebElement usernameField = driver.findElement(By.name("username"));

    usernameField.sendKeys("testUser");

    WebElement genderRadio = driver.findElement(By.name("gender"));

    genderRadio.click();

    If multiple elements share the same name, findElements() can retrieve all matches for further filtering.

    4. Locating Elements by XPath

    XPath locators navigate the DOM hierarchy to identify elements based on attributes, position, or text. This is especially useful for complex or dynamic pages where IDs or class names may not be reliable.

    For example, to locate a text input and a link with specific text:

    WebElement searchBox = driver.findElement(By.xpath("//input[@type='text']"));

    searchBox.sendKeys("Selenium");

    WebElement homeLink = driver.findElement(By.xpath("//div[@class='menu']//a[text()='Home']"));

    homeLink.click();

    Relative XPath expressions are preferred because they are less likely to break when the DOM structure changes.

    5. Locating Elements by Tag Name

    Tag name locators identify elements based on their HTML tag. This method is useful when you want to interact with all elements of a particular type, such as all input fields, buttons, or links on a page. It can also be combined with other locators to filter specific elements.

    For example, to find the first input field on a page, you can use:

    WebElement inputField = driver.findElement(By.tagName("input"));

    inputField.sendKeys("test value");

    If you want to retrieve all input fields and work with a specific one, use findElements():

    List<WebElement> inputs = driver.findElements(By.tagName("input"));

    inputs.get(2).sendKeys("value for third input");

    This approach is useful when the tag is consistent but attributes like ID or class vary across elements.

    6. Locating Elements by Link Text

    Link text locators find hyperlinks based on their visible text. This is useful when the exact link text is known and unique.

    For example, to click a “Home” link:

    WebElement homeLink = driver.findElement(By.linkText("Home"));

    homeLink.click();

    7. Locating Elements by Partial Link Text

    Partial link text locators match a portion of the visible text of a hyperlink. This is helpful when link text is long, dynamic, or only partially predictable.

    For example, to click a link containing the word “Contact”:

    WebElement contactLink = driver.findElement(By.partialLinkText("Contact"));

    contactLink.click();

    How to Locate Multiple Elements in Selenium

    In many scenarios, a page contains multiple elements of the same type or class, such as rows in a table, multiple buttons, or repeated form fields. Selenium provides methods to locate all matching elements at once, enabling testers to iterate through them, apply conditional logic, or perform bulk actions.

    The primary method for this is findElements(), which returns a list of WebElement objects instead of a single element. Unlike findElement(), which throws an exception if the element is not found, findElements() returns an empty list when no matches exist, allowing safer handling in scripts.

    For example, to retrieve all input fields on a form and fill them sequentially:

    List<WebElement> inputFields = driver.findElements(By.tagName("input"));

    inputFields.get(0).sendKeys("first input");

    inputFields.get(1).sendKeys("second input");

    Another common scenario is handling multiple buttons or links sharing the same class:

    List<WebElement> buttons = driver.findElements(By.className("submit-button"));

    for (WebElement button : buttons) {

        if (button.getText().equals("Save")) {

            button.click();

            break;

        }

    }

    How to Choose the Right Locator in Selenium

    Selecting the right locator is essential for creating reliable, maintainable, and efficient automation scripts. The following points guide testers in making the best choice:

    • Check for a unique ID first: If the element has a static and unique id, use it. This is the fastest and most stable locator for Selenium.
    • Use name or class attributes when IDs are unavailable: Ensure that these attributes are consistent and not dynamically generated. If multiple elements share the same class or name, combine with other attributes or use findElements() to filter.
    • Leverage XPath or CSS selectors for complex elements: When elements are nested or lack unique attributes, relative XPath or CSS selectors allow precise navigation within the DOM hierarchy.
    • Combine multiple attributes for accuracy: Using a combination of tag, class, and other attributes ensures the correct element is targeted, reducing the risk of interacting with the wrong element.
    • Consider element stability over time: Avoid dynamic or frequently changing attributes. Prefer stable, predictable properties like parent containers or text content when available.
    • Evaluate performance impact: Simple locators like IDs are faster, while complex XPath expressions can slow down execution, especially for large test suites. Choose locators that balance reliability and speed.

    Best Practices for Using Locators in Selenium

    Using locators effectively requires more than knowing the syntax. Following best practices ensures your scripts remain stable, maintainable, and efficient across dynamic web applications. Below are key recommendations:

    • Prefer unique IDs whenever possible: IDs are usually unique and allow Selenium to locate elements quickly. This reduces DOM traversal time and makes scripts faster and more reliable.
    • Use relative XPath over absolute XPath: Absolute paths depend on the full DOM structure and break easily when the page layout changes. Relative XPath like //div[@class='container']//button[text()='Submit'] is more flexible and resilient.
    • Combine attributes for precision: When IDs or classes are not unique, combine multiple attributes in CSS selectors or XPath. For example, selecting an input by type and placeholder ensures the correct field is targeted.
    • Avoid dynamic attributes if possible: Elements with dynamically generated IDs or class names may differ on each page load. If unavoidable, use stable parent elements or relative paths to locate them.
    • Use findElements() for multiple matches: When multiple elements share the same locator, findElements() returns a list, allowing you to filter or iterate safely instead of risking NoSuchElementException.
    • Validate locator reliability during maintenance: Periodically check locators after UI changes or browser updates. Stable locators reduce test failures and maintenance effort.
    • Integrate waits when locating dynamic elements: Elements may load asynchronously. Using explicit waits like WebDriverWait ensures that elements are visible and interactable before performing actions.
    • Test across browsers and devices: Locators may behave differently in Chrome, Firefox, or Edge, especially for dynamic content. Validate scripts across real devices and browsers for consistency. Platforms like BrowserStack can simplify this process by providing access to multiple real devices and browser combinations without managing hardware.

    Conclusion 

    Locators in Selenium are essential for reliable and maintainable automation scripts. Selecting the right locator type and handling dynamic elements ensures that scripts interact with the correct elements, remain stable after UI changes, and perform efficiently across complex web pages.

    Platforms like BrowserStack allows testers to run Selenium scripts across multiple real devices and browsers. This helps identify browser-specific issues, validate locators in different environments, and ensures consistent performance and accuracy without managing physical hardware.

    Run Selenium Tests on Cloud

    Data-rich bug reports loved by everyone

    Get visual proof, steps to reproduce and technical logs with one click

    Make bug reporting 50% faster and 100% less painful

    Rating LogosStars
    4.6
    |
    Category leader

    Liked the article? Spread the word

    Put your knowledge to practice

    Try Bird on your next bug - you’ll love it

    “Game changer”

    Julie, Head of QA

    star-ratingstar-ratingstar-ratingstar-ratingstar-rating

    Overall rating: 4.7/5

    Try Bird later, from your desktop