Skip to content
All notes
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

  1. Prefer ID when available (fastest and most reliable)
  2. Use CSS Selector over XPath when possible (better performance)
  3. Avoid absolute XPath (brittle, breaks easily)
  4. Use data-testid or custom attributes for test automation
  5. Keep locators maintainable and readable
  1. ID
  2. Name
  3. CSS Selector
  4. XPath (as last resort)