Sobes.tech
Junior

What locators are available in Selenium?

sobes.tech AI

Answer from AI

Locators in Selenium are mechanisms for finding web elements on a page. The main types of locators:

  • ID: Allows finding an element by its id attribute. The fastest and most reliable method if the ID is unique and stable.
  • Name: Allows finding an element by its name attribute. Less reliable than ID, as name is not always unique.
  • Class Name: Allows finding elements by their class attribute. Returns a list of elements, as multiple elements can have the same class.
  • Tag Name: Allows finding elements by the HTML tag name (e.g., div, a, input). Returns a list of elements.
  • Link Text: Allows finding an <a> element (link) by the exact link text.
  • Partial Link Text: Allows finding an <a> element (link) by partial match of the link text.
  • CSS Selector: A powerful and flexible way to find elements using CSS selector syntax. Allows searching by a combination of attributes, tags, classes, hierarchy, and states.
  • XPath: The most powerful and flexible way to find elements, based on navigating the structure of an XML/HTML document. Allows building complex paths to elements, searching by attributes, content, and position.

Examples of usage:

# Java
WebElement elementById = driver.findElement(By.id("myElementId"));
WebElement elementByName = driver.findElement(By.name("elementName"));
List<WebElement> elementsByClass = driver.findElements(By.className("myClass"));
WebElement elementByCss = driver.findElement(By.cssSelector("div.container > input[type='text']"));
WebElement elementByXpath = driver.findElement(By.xpath("//div[@id='parent']/button[text()='Submit']"));
# Python
element_by_id = driver.find_element(By.ID, "myElementId")
element_by_name = driver.find_element(By.NAME, "elementName")
elements_by_class = driver.find_elements(By.CLASS_NAME, "myClass")
element_by_css = driver.find_element(By.CSS_SELECTOR, "div.container > input[type='text']")
element_by_xpath = driver.find_element(By.XPATH, "//div[@id='parent']/button[text()='Submit']")

The choice of locator depends on the stability of the web element and the page structure. It is recommended to use ID, CSS Selector, or XPath when they are properly constructed.