Sobes.tech
Junior

What selectors in HTML can be used by an automation tool for writing UI autotests?

sobes.tech AI

Answer from AI

An automator can use the following selectors in HTML to write UI tests:

  • By ID: The most reliable if the ID is unique. element = driver.find_element(By.ID, "my-element-id")
  • By Name: Finds elements by the name attribute. element = driver.find_element(By.NAME, "username")
  • By Class Name: Finds elements by the class attribute. Can return multiple elements. elements = driver.find_elements(By.CLASS_NAME, "button-primary")
  • By Tag Name: Finds elements by the tag name. elements = driver.find_elements(By.TAG_NAME, "a")
  • By Link Text: Finds <a> elements by exact link text match. element = driver.find_element(By.LINK_TEXT, "На главную")
  • By Partial Link Text: Finds <a> elements by partial link text match. element = driver.find_element(By.PARTIAL_LINK_TEXT, "главн")
  • By CSS Selector: A powerful and flexible way to find elements using CSS syntax. element = driver.find_element(By.CSS_SELECTOR, "div.container > p#welcome-message")
  • By XPath: The most flexible and powerful, but can be less readable and more fragile. Allows searching through the entire DOM tree. element = driver.find_element(By.XPATH, "//input[@type='text' and @name='email']")

The choice of selector depends on the page structure, the presence of unique attributes, and the required flexibility. CSS and XPath are the most commonly used for complex scenarios.

Examples of usage in Python with Selenium WebDriver:

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome() # Or another browser

# By ID
element_by_id = driver.find_element(By.ID, "submit-button")

# By Class Name
elements_by_class = driver.find_elements(By.CLASS_NAME, "error-message")

# By CSS Selector
element_by_css = driver.find_element(By.CSS_SELECTOR, "#login-form input[type='password']")

# By XPath
element_by_xpath = driver.find_element(By.XPATH, "//label[text()='Имя пользователя']/following-sibling::input")

driver.quit()
What selectors in HTML can be used by an automation… - sobes.tech