Sobes.tech
Junior — Middle

How do I select and create locators for elements on a page?

sobes.tech AI

Answer from AI

Choosing and creating locators for page elements is a key task in test automation. Main principles:

  1. Uniqueness — the locator should unambiguously identify the element.
  2. Stability — the locator should remain valid despite interface changes.
  3. Simplicity and readability — the locator should be understandable and maintainable.

Types of locators:

  • ID — the most preferred if the element has a unique id attribute.
  • Name — if id is not available, the name attribute can be used.
  • CSS selectors — flexible, allow selecting elements by classes, attributes, structure.
  • XPath — powerful but can be fragile and complex.

Example of creating a locator in Selenium (Python):

from selenium.webdriver.common.by import By

# By ID
locator = (By.ID, "submit-button")

# By CSS selector
locator = (By.CSS_SELECTOR, "div.content > button.primary")

# By XPath
locator = (By.XPATH, "//button[text()='Submit']")

When choosing a locator, prefer ID or unique attributes, then CSS, and only if no other options are available — XPath.

How do I select and create locators for elements on a… - sobes.tech