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:
- Uniqueness — the locator should unambiguously identify the element.
- Stability — the locator should remain valid despite interface changes.
- Simplicity and readability — the locator should be understandable and maintainable.
Types of locators:
- ID — the most preferred if the element has a unique
idattribute. - Name — if
idis not available, thenameattribute 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.