32SeleniumAutomationSelenium
What are different types of locators in Selenium?
Locators are used to identify and interact with web elements on a page. Selenium provides multiple strategies to locate elements.
Types of Locators
1. ID:
- Most reliable and fastest
- Should be unique on the page
- Example:
driver.find_element(By.ID, "username")
2. Name:
- Uses the name attribute
- May not be unique
- Example:
driver.find_element(By.NAME, "email")
3. Class Name:
- Uses CSS class attribute
- Often not unique (multiple elements can share same class)
- Example:
driver.find_element(By.CLASS_NAME, "btn-primary")
4. Tag Name:
- Uses HTML tag name
- Useful for finding all elements of a type
- Example:
driver.find_elements(By.TAG_NAME, "input")
5. Link Text:
- For anchor tags with exact text match
- Example:
driver.find_element(By.LINK_TEXT, "Click Here")
6. Partial Link Text:
- For anchor tags with partial text match
- Example:
driver.find_element(By.PARTIAL_LINK_TEXT, "Click")
7. CSS Selector:
- Powerful and flexible
- Faster than XPath
- Example:
driver.find_element(By.CSS_SELECTOR, "#username") - Example:
driver.find_element(By.CSS_SELECTOR, ".btn-primary") - Example:
driver.find_element(By.CSS_SELECTOR, "input[type='email']")
8. XPath:
- Most powerful but slower
- Can traverse up and down the DOM
- Absolute XPath:
//html/body/div/form/input - Relative XPath:
//input[@id='username'] - Example:
driver.find_element(By.XPATH, "//button[text()='Submit']")
Best Practices
- Prefer ID when available (fastest and most reliable)
- Use CSS Selector over XPath when possible (better performance)
- Avoid absolute XPath (brittle, breaks easily)
- Use data-testid or custom attributes for test automation
- Keep locators maintainable and readable
Locator Priority (Recommended Order)
- ID
- Name
- CSS Selector
- XPath (as last resort)