Locators in Selenium
In Selenium, locators are used to identify and interact with elements on a web page (like buttons, text fields, dropdowns, etc.). Selenium WebDriver provides several types of locators to find elements efficiently.
Types of Locators in Selenium
1. ID Locator
- Finds an element by its id attribute (unique on a page).
# Syntax
driver.findElement(By.id("element-id"));
# html code
<input id="username" type="text">
# Example
WebElement username = driver.findElement(By.id("username"));
2. Name Locator
- Finds elements by their name attribute (not always unique).
# Syntax
driver.findElement(By.name("element-name"));
# html code
<input name="email" type="text">
# Example
WebElement email = driver.findElement(By.name("email"));
3. CSS Selector
- Uses XML path expressions to navigate the DOM.
# Syntax
driver.findElement(By.cssSelector("css-selector"));
# html code
#username /* By ID */
.btn-submit /* By Class */
input[name='email'] /* By Attribute */
div > p /* Child Selector */
4. XPath Locator #
- Uses XML path expressions to navigate the DOM.
# Syntax
driver.findElement(By.xpath("xpath-expression"));
# html code
//input[@id='username'] /* Finds by ID */
//*[contains(text(),'Login')] /* Partial text match */
//div[@class='container']/a /* Child element */
5. Link Text
- Link Text: Finds a link by its exact text.
# html code
<a href="/reset">Forgot Password?</a>
# Example for link Text
driver.findElement(By.linkText("Forgot Password?"));
6. Partial Link Text
- Partial Link Text: Finds a link by partial text match.
# html code
<a href="/reset">Forgot Password?</a>
# Example for partia
l link text
driver.findElement(By.partialLinkText("Forgot"));
7. Class Name Locator
- Finds elements by their class attribute (can match multiple elements).
# Syntax
driver.findElement(By.className("class-name"));
# html code
<button class="btn-submit">Submit</button>
# Example
WebElement submitBtn = driver.findElement(By.className("btn-submit"));
8. Tag Name Locator
- Finds elements by their HTML tag (e.g., <div>, <a>, <input>).
# Syntax
driver.findElement(By.tagName("tag-name"));
# html code
<a href="/login">Login</a>
# Example
WebElement link = driver.findElement(By.tagName("a"));
Which Locator to Use?
Locator | When to Use |
ID | Best (if unique) |
Name | Good for forms |
CSS Selector | Faster than XPath, flexible |
XPath | Complex traversals (parent/child) |
Link Text | Only for hyperlinks |
Class/Tag | Less reliable (often multiple matches) |
Best Practices
- Prefer ID or Name (if available, as they are fastest).
- Use CSS Selector for better performance than XPath.
- Avoid XPath for simple cases (slower in older browsers).
- Use relative XPath (//) instead of absolute (/html/…).
- Avoid dynamic attributes (e.g., id=”button-1234″ changes frequently).
Locators are fundamental in Selenium automation, and choosing the right one improves script stability and performance.