Introduction
Selenium WebDriver is widely used for automating web applications. One of the most important skills in Selenium automation is identifying and locating web elements accurately.
Before Selenium can click a button, enter text into a field, select an option or verify information, it must identify the relevant element on the webpage. Selenium uses locators to find these elements.
Understanding locators such as ID, Name, Class Name, CSS Selector and XPath is essential for developing reliable automation scripts.
In this guide, we will explore the most commonly used Selenium locators with practical Java examples.
What Are Locators in Selenium?
Locators are methods used by Selenium WebDriver to identify HTML elements on a webpage.
For example, consider a login form containing:
Username field
Password field
Login button
Selenium needs to locate each element before interacting with it.
A typical HTML element may look like this:
<input id="username" name="user" type="text">Selenium can identify this field using its ID or Name attribute.
1. ID Locator
The ID locator identifies an element using its unique HTML ID attribute.
HTML example:
<input id="email" type="text">Java example:
driver.findElement(By.id("email")).sendKeys("test@example.com");Advantages:
Simple and easy to use.
Usually fast and reliable.
Works well when IDs are unique and stable.
Limitation: Some websites generate dynamic IDs, which may change between sessions.
2. Name Locator
The Name locator identifies an element through its HTML Name attribute.
HTML example:
<input name="password" type="password">Java example:
driver.findElement(By.name("password")).sendKeys("Test@123");Name locators are useful for forms where elements have meaningful and stable name attributes.
If multiple elements share the same name, Selenium may locate the first matching element when using findElement().
3. Class Name Locator
The Class Name locator identifies elements using their CSS class attribute.
HTML example:
<button class="login-button">Login</button>Java example:
driver.findElement(By.className("login-button")).click();Class Name is useful when elements share a common class.
However, By.className() accepts a single class name, not a compound class string containing multiple classes.
4. Tag Name Locator
Tag Name identifies elements using HTML tags such as input, button, a, div or select.
Java example:
driver.findElement(By.tagName("button")).click();It can also be used to retrieve multiple elements:
List<WebElement> buttons =
driver.findElements(By.tagName("button"));
System.out.println("Total buttons: " + buttons.size());Tag Name is particularly useful when working with groups of similar elements.
5. CSS Selector in Selenium
CSS Selector is a powerful locator strategy that identifies elements using CSS selector syntax.
ID-based CSS Selector:
driver.findElement(By.cssSelector("#email"));Class-based CSS Selector:
driver.findElement(By.cssSelector(".login-button"));Attribute-based CSS Selector:
driver.findElement(
By.cssSelector("input[name='password']")
);Combining attributes:
driver.findElement(
By.cssSelector("input[type='text'][name='username']")
);CSS Selectors are generally concise and useful for locating elements through IDs, classes, attributes and relationships.
6. XPath in Selenium
XPath is a query language used to navigate through elements in an HTML or XML document.
It is especially useful when elements do not have unique IDs or when locating elements through their text, attributes or relationships.
Absolute XPath
An absolute XPath starts from the root of the HTML document and follows the complete element hierarchy.
Example:
driver.findElement(
By.xpath("/html/body/div/form/input")
);Absolute XPath can be fragile because changes in the page structure may break the locator.
Relative XPath
Relative XPath starts from a selected point in the document.
Example:
driver.findElement(
By.xpath("//input[@id='email']")
);Relative XPath is generally preferred because it is more flexible.
XPath Using Text
driver.findElement(
By.xpath("//button[text()='Login']")
).click();XPath Using Contains
driver.findElement(
By.xpath("//button[contains(@class,'login')]")
).click();XPath Using Starts-With
driver.findElement(
By.xpath("//input[starts-with(@id,'user')]")
);XPath Using Multiple Attributes
driver.findElement(
By.xpath("//input[@type='text' and @name='username']")
);These techniques are particularly useful when automating dynamic web applications.
7. Selenium Locators Comparison
| Locator | Example | Typical use |
|---|---|---|
| ID | By.id("email") | Unique element ID |
| Name | By.name("user") | Form fields |
| Class Name | By.className("btn") | Elements with a class |
| Tag Name | By.tagName("input") | Groups of HTML elements |
| CSS Selector | By.cssSelector("#email") | Flexible attribute and class selection |
| XPath | By.xpath("//input[@id='email']") | Complex element relationships |
There is no single locator that is best for every situation. Choose a locator based on uniqueness, stability, readability and maintainability.
8. Practical Selenium Java Example
The following example demonstrates locating and interacting with elements using different locator strategies.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class LocatorExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
driver.findElement(By.id("username"))
.sendKeys("testuser");
driver.findElement(By.name("password"))
.sendKeys("Test@123");
driver.findElement(
By.cssSelector("button.login-button")
).click();
driver.quit();
}
}Replace the example URL and locator values with those from your own test application.
9. Best Practices for Using Selenium Locators
Follow these practices to build stable automation scripts:
Prefer unique and stable IDs whenever available.
Use Name attributes when they are meaningful and reliable.
Use CSS Selectors for concise attribute-based identification.
Use relative XPath for complex element identification.
Avoid fragile absolute XPath expressions.
Avoid relying on automatically generated IDs that frequently change.
Use browser developer tools to inspect HTML elements.
Keep locators readable and maintainable.
Validate that a locator identifies the intended element.
Use explicit waits when elements need time to become available or interactable.
Frequently Asked Questions
1. Which locator is best in Selenium?
A unique, stable ID is often a good first choice. CSS Selector and XPath are useful alternatives depending on the webpage structure.
2. What is the difference between XPath and CSS Selector?
Both can identify elements using attributes and relationships. XPath also supports text-based matching and flexible navigation through the document hierarchy.
3. Can Selenium use multiple locators for the same element?
Yes. An element may be identifiable using different locator strategies. You should choose the most reliable and maintainable one.
4. What is the difference between findElement() and findElements()?
findElement() returns the first matching element and throws a NoSuchElementException if no match exists. findElements() returns a list of matching elements and returns an empty list when none are found.
5. Do I need to learn XPath for Selenium automation?
Yes. XPath is an important skill, particularly when working with complex or dynamic web applications.
Learn Selenium Automation Testing with Palium Skills
Want to build practical skills in Selenium automation testing? Palium Skills offers structured training designed for freshers, manual testers and working professionals.
The training covers:
Selenium WebDriver with Java and Python
XPath and CSS Selector techniques
TestNG and PyTest frameworks
Page Object Model (POM)
Automation framework development
API testing and practical automation projects
Interview preparation and career guidance
Training modes: Classroom training at South Kolkata and Salt Lake centres, along with instructor-led live online training for learners across India.
Contact Palium Skills
Website: www.paliumskills.com
Call: 8420594969 / 7044871915
WhatsApp: 9903130500
Email: info@paliumskills.com
South Kolkata Centre: 1st Floor, Sheeba Bhavan, 1/22 Poddar Nagar (Near South City Mall), Kolkata – 700068.
Salt Lake Centre: 5th Floor, RDB Boulevard, Block GP, Salt Lake Electronic Complex, Kolkata – 700091.
Visit Palium Skills to explore Selenium and Playwright automation testing training.
No comments:
Post a Comment