What are the different types of locators in Selenium?

Selenium is a popular web testing library used to automate browser activities. Selenium supports eight types of locators to select elements on the page. You can use the most appropriate one for your case. Selenium provides the following methods to locate elements in a page:

  • ID: Select element with the specified @id attribute. If more than one element has the same id, the first one will be selected.

Python:

element = driver.find_element_by_id("element_id")

JavaScript:

const element = driver.findElement(By.id("element_id"));
  • Name: Selects the first element with the specified @name attribute.

Python:

element = driver.find_element_by_name("element_name")

JavaScript:

const element = driver.findElement(By.name("element_name"));
  • Class Name: Selects elements with the specified class name.

Python:

element = driver.find_element_by_class_name("element_class")

JavaScript:

const element = driver.findElement(By.className("element_class"));
  • Tag Name: Selects elements with the specified tag name.

Python:

element = driver.find_element_by_tag_name("element_tag")

JavaScript:

const element = driver.findElement(By.tagName("element_tag"));
  • Link Text: Selects the hyperlink element with the exact text match.

Python:

element = driver.find_element_by_link_text("link_text")

JavaScript:

const element = driver.findElement(By.linkText("link_text"));
  • Partial Link Text: Selects the hyperlink element which contains the specified text.

Python:

element = driver.find_element_by_partial_link_text("partial_link_text")

JavaScript:

const element = driver.findElement(By.partialLinkText("partial_link_text"));
  • CSS Selector: Selects elements based on the CSS selector.

Python:

element = driver.find_element_by_css_selector("css_selector")

JavaScript:

const element = driver.findElement(By.css("css_selector"));
  • XPath: Selects elements based on the XPath expression. XPath is a language used for navigating through an XML document.

Python:

element = driver.find_element_by_xpath("xpath")

JavaScript:

const element = driver.findElement(By.xpath("xpath"));

Each method in Python has a corresponding method that starts with find_elements_by_ to return a list if there are multiple matches.

In JavaScript, to select multiple elements, use driver.findElements (note the plural 'Elements').

Remember to choose the most appropriate and reliable locator according to your scenario. It's recommended to use ID, Name, or CSS Selector where possible, as they are the most efficient and reliable. XPath should be used as a last resort, and only when other locators are not available, as it is the slowest and most brittle.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon