We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Apply a priority strategy for choosing locators and build reusable patterns for real projects.
In this unit, we explored the full spectrum of Selenium locator strategies. Choosing the right locator is the single most important factor in creating stable, maintainable tests.
When inspecting an element, always look for locators in this order:
By.id): Fastest and most unique.By.name): Great for form fields.By.cssSelector): Powerful, flexible, and faster than XPath.By.xpath): The "nuclear option" for complex traversals or text-based lookup.with(By...) to find elements based on visual layout (above, below, near)./html/body/div[2]/div[5]/button. They break with the slightest UI change. Always prefer relative paths or attributes.Here is a script that combines multiple locator strategies to interact with a complex page structure.
123456789101112131415161718192021// 1. ID for the main container or form
WebElement loginForm = driver.findElement(By.id("login-modal"));
// 2. Name for input fields
WebElement username = driver.findElement(By.name("user_login"));
// 3. CSS Selector for complex attributes (e.g., data-testid)
WebElement password = driver.findElement(By.cssSelector("input[data-testid='password-field']"));
// 4. XPath for text-based button lookup
WebElement loginBtn = driver.findElement(By.xpath("//button[text()='Sign In']"));
// 5. Relative Locator for a "Forgot Password" link below the password field
WebElement forgotLink = driver.findElement(
RelativeLocator.with(By.tagName("a")).below(password)
);
// Interaction
username.sendKeys("admin");
password.sendKeys("securePass123");
loginBtn.click();If you find yourself writing complex XPaths, ask developers to add id or data-testid attributes.
Browsers optimize CSS selectors better than XPath. Use XPath only when you need to traverse up the DOM or search by text.
Always verify your locator in the Chrome DevTools Console ($x("...") or $$("...")) to ensure it matches exactly one element.