Selenium Locators
A locator tells Selenium exactly which element on a page to interact with. Think of a webpage as a crowded room and a locator as a name tag that helps Selenium find one specific person in that room.
Diagram: A Webpage As A Room Of Elements
[Page] |-- Button (id="submit") |-- Input (name="username") |-- Link (class="nav-link") |-- Image (tag="img") |-- Div (xpath target)
Selenium needs one unique tag from this list to click, type, or read the correct element.
Eight Locator Strategies
By.id
Finds an element using its id attribute. IDs are usually unique on a page, making this the fastest and most reliable locator.
driver.findElement(By.id("email"));By.name
Finds an element using its name attribute, common on form fields.
driver.findElement(By.name("password"));By.className
Finds an element using its CSS class value.
driver.findElement(By.className("btn-primary"));By.tagName
Finds an element using its HTML tag, like a or img.
driver.findElement(By.tagName("a"));By.linkText
Finds a hyperlink using its exact visible text.
driver.findElement(By.linkText("Contact Us"));By.partialLinkText
Finds a hyperlink using part of its visible text.
driver.findElement(By.partialLinkText("Contact"));By.cssSelector
Finds an element using CSS selector syntax, covered fully in a later topic.
driver.findElement(By.cssSelector("input#email"));By.xpath
Finds an element using XPath syntax, covered fully in a later topic.
driver.findElement(By.xpath("//input[@id='email']"));Choosing The Right Locator
| Situation | Best Locator |
|---|---|
| Element has a unique ID | By.id |
| Element is a form field | By.name |
| Element is a link with clear text | By.linkText |
| No ID or name available | By.cssSelector or By.xpath |
findElement Versus findElements
findElement() returns one single matching element and throws an error if nothing matches. findElements() returns a list of every matching element and returns an empty list if nothing matches. Use findElements() when a page has many similar items, like a list of product cards.
List<WebElement> products = driver.findElements(By.className("product-card"));
System.out.println("Total products: " + products.size());
This script counts how many product cards appear on a page, useful for checking search results or catalog listings.
