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.
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:
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:
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:
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.
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.
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
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.
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.
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.
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();
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();
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;
}
}
Selecting the right locator is essential for creating reliable, maintainable, and efficient automation scripts. The following points guide testers in making the best choice:
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:
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
Get visual proof, steps to reproduce and technical logs with one click
Continue reading
Try Bird on your next bug - you’ll love it
“Game changer”
Julie, Head of QA
Try Bird later, from your desktop