Locators in Selenium: A Detailed Guide

Use Locators in Selenium to locate elements on Real Devices and Browsers

Get Started free
Guide Banner Image
Home Guide Locators in Selenium: A Detailed Guide

Locators in Selenium: A Detailed Guide

Locators in Selenium WebDriver are used to identify and interact with WebElements within a web page’s Document Object Model (DOM). They serve as the foundation for automating web application tests by allowing testers to perform actions such as clicking buttons, entering text, or verifying content.

Locators play a critical role in finding elements on a webpage which supports effective interaction with web elements in automated testing with Selenium WebDriver.

Some locators may be faster than others depending on the complexity of the page, so selecting the right locator can significantly impact test performance. This guide discusses different types of locators in detail highlighting when to use which and best practices for efficient web automation testing.

What are Locators in Selenium?

Locators in Selenium are essential tools that enable automated tests to identify and interact with elements on a web page within the Document Object Model (DOM). They act as unique identifiers for web elements, allowing testers to perform various actions such as clicking buttons, entering text, or validating the presence of elements.

Selenium provides different locator such as ID, Name, TagName, ClassName, XPath, CSS Selector, LinkText, and PartialLinkText. Each of the Locator type is suited to different scenarios based on the structure and attributes of the web page.

By mastering the use of locators, testers can effectively ensure their scripts interact accurately with the web application, leading to successful and efficient test execution.

What are Selenium Locators used for?

Selenium Locators are used for different purposes such as:

  • Identify and Interact with Web Elements: Locators in Selenium are primarily used to identify and interact with web elements on a webpage during automated testing. They serve as the means through which Selenium WebDriver can locate specific elements in the Document Object Model (DOM).
  • Perform different actions, such as clicking buttons, entering text into fields, selecting options from dropdown menus, checking or unchecking checkboxes, and verifying the presence and state of elements are performed using Selenium Locators.
  • Check functionality on web pages: Locators facilitate crucial verifications within test scripts. They help determine whether a web element is present, visible, and interactable, as well as its current state, such as enabled or disabled.
    This capability is essential for ensuring that the user interface operates correctly, as it reflects real-world user interactions.
  • Avoid Flaky Tests: Correct usage of locators is vital to avoid flaky tests, which can lead to inconsistent results and unnecessary test failures. Utilizing the right locator strategies not only enhances the reliability of test scripts but also contributes to efficient test execution.
  • Saving Time and Effort: Implementing appropriate locator techniques can help testers streamline the process of writing automated tests, ultimately saving time and effort while increasing the effectiveness of their testing efforts.
  • Improves Test Maintainability: A well-chosen locator not only enhances the stability of tests but also contributes to their readability and maintainability.

Different Types of Locators in Selenium

Here’s a snapshot overview of top 8 locators in Selenium:

  1. By CSS ID: find_element_by_id
  2. By CSS class name: find_element_by_class_name
  3. By name attribute: find_element_by_name
  4. By DOM structure or Xpath: find_element_by_xpath
  5. by tagName: find_element_by_tag_name()
  6. By link text: find_element_by_link_text
  7. By partial link text: find_element_by_partial_link_text
  8. By HTML tag name: find_element_by_tag_name

While all these locators return single elements, one may use the .find_elements() method to find multiple elements. Let’s further explore the different types of locators in Selenium and how to use them.

Locators in Selenium WebDriver are crucial for identifying elements on a web page. Each locator type has its own syntax and is suited for different scenarios based on the structure of the HTML and the attributes of the elements.

The following table outlines the various types of locators available in Selenium, along with their descriptions and syntax.

Locator TypeDescriptionSyntax
IDLocates an element using its unique ID attribute. This is one of the fastest and most reliable locator types.driver.findElement(By.id(“elementID”));
NameFinds elements by their name attribute. This can be useful when multiple elements share the same name.driver.findElement(By.name(“elementName”));
Class NameTargets elements based on their class attribute. This is useful for selecting multiple elements that share a class.

driver.findElement(By.className(“className”));
Tag NameLocates elements by their tag name (e.g., input, button, div). This can be used to find all elements of a specific type.driver.findElement(By.tagName(“tagName”));
Link TextSpecifically used to locate anchor (<a>) elements by their visible text. This is helpful for finding links.driver.findElement(By.linkText(“Visible Text”));
Partial Link TextSimilar to Link Text, but allows for partial matching of the anchor text, making it useful for long or dynamic link text.driver.findElement(By.partialLinkText(“Partial Text”));
XPathA powerful and flexible locator that uses XML path language to navigate through elements and attributes in the DOM.driver.findElement(By.xpath(“//tag[@attribute=’value’]”));
CSS SelectorUtilizes CSS selectors to find elements. This is often faster than XPath and can be very expressive for complex selections.driver.findElement(By.cssSelector(“cssSelector”));

Understanding these locator types and their appropriate syntax is essential for creating effective automated test scripts in Selenium, as the choice of locator can significantly impact the reliability and performance of the tests.

Locate Elements by CSS ID

This is by far the simplest method of locating an element. The CSS ID, stored in the id attribute of an HTML DOM element, is unique for every element in the page by design. Thus, an ID can uniquely identify an element.

To use this feature, one needs to call the .find_element_by_id() method of the webdriver class. Here is the usage for it.

from selenium import webdriver

driver = webdriver.Chrome('./chromedriver')
driver.get("https://www.python.org")

search_bar = driver.find_element_by_id("id-search-field")

If there is no DOM element with the ID that one is searching for, a NoSuchElementException is raised, which one can account for, by using a try-catch block.

Theoretically, every DOM element on a page should have a unique ID. However, in real life, one does not commonly observe this. Most elements may not have an ID or encounter two elements with the same ID. In such cases, one needs to use a different strategy to identify a DOM element uniquely.

BrowserStack Automate Banner 7

Locate Elements by CSS Class

A second strategy for locating elements on a page is to search by the class name. The class name is stored in the class attribute of an HTML tag. By design, a CSS class applies to a group of DOM elements. The .find_element_by_class_name() method only returns the first element with the matching class. It raises a NoSuchElementException if no element exists with the given class name. Here is how to use the method in the driver.

from selenium import webdriver

driver = webdriver.Chrome('./chromedriver')
driver.get("https://www.python.org")

# Returns first element with matching class
first_search_bar = driver.find_element_by_class_name("id-class-name")

Locate Elements by Name

In HTML5, form elements often have a name attribute associated with them. The .find_element_by_name() method only returns the first element with the matching class. If multiple elements of the same name exist, the first matched element will be returned. No matching elements result in a NoSuchElementException error.

Consider the following form:

<form id="loginForm">
<input name="name" type="text" value="First Name" />
<input name="name" type="text" value="Last Name" />
<input name="email" type="text" value="Business Email" />
<input name="password" type="password" />
<input name="continue" type="submit" value="Sign Me Up" />
</form>

The following code returns the email form element.

email_input = driver.find_element_by_name("email")

However, the following code only returns the first name form element.

name_input = driver.find_element_by_name("name")

Using the .find_element_by_name() method, it is impossible to get to the last name input form field in the example. This brings us to the next locator.

Locate Elements by XPath

If one has failed to identify an element by ID, class, or name, one would need to locate the element through its XML path. This process may also be implemented while reading an XML document. In this tutorial, we explore the use of relative paths, as absolute paths are prone to errors with the slightest change in the HTML structure.

We will use the .find_element_by_xpath() method to locate an appropriate element in the document. The argument that the .find_element_by_xpath() method takes is the path to the element.

To find the email input field in the above HTML form example, use the following code:

email_input = driver.find_element_by_xpath("//form[input/@name='email']")

This code snippet searches for the first form element of the page. Within this form, it searches for input with the name, which equals the value email, thus narrowing down to the required element.

Next, let us try to locate the form’s first and last names input element above.

first_name = driver.find_element_by_xpath("//form[@id='loginForm']/input[1]")
last_name = driver.find_element_by_xpath("//form[@id='loginForm']/input[2]")

The method first searches for a form with the ID login form and then selects the form’s first and second input elements as the first and last names.

Locate Elements by tagName

In addition to the popular methods we have discussed, there are a few other element locators in the Selenium WebDriver that testers may wish to explore.

One can locate elements by their HTML tag name using the .find_element_by_tag_name() method.

page_heading = driver.find_element_by_tag_name('h1')

Locate Elements by linkText

One can also search for a hyperlink element using the link text. One can either use the .find_element_by_link_text() method to search for the exact link’s text.

# Exact Link Text
click_here_link = driver.find_element_by_link_text('Click Here')

Locate Elements by partialLinkText

Or one can also search for a hyperlink element using the partial link text .find_element_by_partial_link_text() method to search for a partial text.

# Partial Link Text 

click_here_link = driver.find_element_by_partial_link_text('Click')

Locate Multiple Elements

In this tutorial, we have discussed methods that locate only single elements. One may want to select a group of elements and then iterate through them. The .find_elements() method helps in finding multiple elements in the DOM structure.

Talk to an Expert

Here are typical examples of the usage of the .find_elements() method. To find all input elements of a form with ID loginForm, use the following snippet –

from selenium.webdriver.common.by import By

all_inputs = driver.find_elements(By.XPATH, '//form[@id='loginForm']/input')

To locate all elements with a class name, use the following code –

from selenium.webdriver.common.by import By

all_elements = driver.find_elements(By.CLASS_NAME, 'my-css-class')

In addition to this, the By class has the following attributes:

  • By.ID: search using the CSS ID
  • By.LINK_TEXT: search using the exact link text
  • By.PARTIAL_LINK_TEXT: search using partial link text
  • By.NAME: search using the name attribute
  • By.TAG_NAME: search using the HTML tag name

Final Thoughts on Locators in Selenium

With this, we come to the end of the tutorial on locators in Selenium using Python. We discussed a variety of approaches to select elements within an HTML page. We first looked at single-element selectors and then moved on to multiple-element selectors in the Selenium WebDriver. Now that you have that cleared out use our Cloud Grid for testing those 8 locators in Selenium.

Which is the most Effective Locator for Selenium?

The most effective locator for Selenium depends on the specific context of the web application being tested. However, generally speaking, the ID locator is often considered the most effective and reliable for several reasons:

  1. Uniqueness: The ID attribute is intended to be unique within a web page, making it straightforward to locate a specific element without ambiguity.
  2. Speed: Using the ID locator is usually the fastest method, as the browser can quickly find elements by their unique identifiers without needing to traverse the DOM extensively.
  3. Stability: Since IDs are less likely to change compared to other attributes (like class names or XPath expressions), tests relying on ID locators tend to be more stable and less prone to breakage.

Other Effective Locators

While the ID locator is typically the preferred choice, other locators can be highly effective in certain situations:

  • CSS Selector: This locator is also very fast and allows for complex queries. It can be particularly useful when dealing with elements that do not have unique IDs but can be identified by class names or other attributes.
  • XPath: While XPath is powerful and versatile, it can be slower and more complex than CSS Selectors. It is particularly useful for navigating deep hierarchies in the DOM or when dealing with elements that do not have unique identifiers.

Ultimately, the choice of locator should be based on the structure of the web application, the stability of the locators, and the specific needs of the test cases being written. Prioritizing the use of unique, stable, and fast locators will lead to more reliable and maintainable automated tests.

Which Selenium Locators to use when?

Choosing the right locator type based on the specific situation is essential for creating stable and effective automated tests in Selenium.

Locator TypeSituation
IDWhen the element has a unique ID attribute, which is stable and unlikely to change.
NameWhen the element has a name attribute, especially useful for form elements like inputs and buttons.
Class NameWhen multiple elements share the same class and you need to interact with any of them.
Tag NameWhen you need to select elements of a specific type, like all input fields or buttons.
Link TextWhen you want to click on a specific hyperlink based on its visible text.
Partial Link TextWhen the visible text of the link may change or is too long, and you only need to match a part of it.
XPathWhen you need to traverse a complex DOM structure or when the element has no unique identifier.
CSS SelectorWhen you need a quick and efficient way to select elements using their CSS properties or when working with complex selections.

Choosing the right locator type based on the specific situation is essential for creating stable and effective automated tests in Selenium.

Best Practices for using Locators in Selenium

When automating tests with Selenium, effectively using locators is crucial for creating reliable and maintainable scripts. Following best practices can help minimize flakiness, improve readability, and enhance test performance. Here are some key best practices to consider:

1. Prefer Unique Locators

Always opt for locators that uniquely identify elements, such as IDs. This reduces ambiguity and increases stability. Example: if the button has a unique ID, use

driver.findElement(By.id("submitBtn"));

2. Avoid Using XPaths When Possible

While XPath is powerful, it can be slower and more complex. Prefer simpler locators like ID or CSS Selectors for better performance.

Example: Instead of using

driver.findElement(By.xpath("//button[@class='submit']"));,

use

driver.findElement(By.cssSelector("button.submit"));.

3. Group Locators by Functionality

Use meaningful names and group locators logically to enhance code readability and maintainability.

Example: Organize locators for login elements together in a LoginPage class.

4. Use CSS Selectors for Complex Scenarios

When elements don’t have unique IDs or names, CSS Selectors can effectively navigate the DOM structure.

Example: For precise targeting use

driver.findElement(By.cssSelector("div.container > input[type='text']"));.

5. Minimize Reliance on Class Names

Since class names can be shared among multiple elements and may change, use them judiciously, primarily in conjunction with other attributes.

Example: Combine class names with other selectors:

driver.findElement(By.cssSelector(".error-message[data-type='warning']"));

6. Be Cautious with Dynamic Elements

For elements that change IDs or classes dynamically (such as, generated by JavaScript), consider using stable attributes or parent elements.

Example: If a button’s ID is dynamic, use a CSS Selector based on its surrounding context:

driver.findElement(By.cssSelector("div#dynamic-container button"));

7. Use Partial Text for Links

For links, using partial link text can be more robust if the full text is subject to change.

Example: locate the link even if the full text changes using partial link text

driver.findElement(By.partialLinkText("Sign Up"));

8. Implement Waits Appropriately

Use explicit waits when interacting with elements that may not be immediately available in the DOM to avoid NoSuchElementExceptions.

Example:

WebDriverWait wait = new WebDriverWait(driver, 10);

WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("dynamicElement")));

9. Use Descriptive Locator Strategies

Ensure locators are descriptive of the elements they target, making it easier for others (or yourself) to understand the test script later.

Example: Use descriptive class names in your CSS Selectors:

driver.findElement(By.cssSelector("input#user-email"));.

10. Regularly Review and Refactor

As the application evolves, revisit and refactor your locator strategies to ensure they remain effective and relevant.

Example: Periodically run tests and adjust locators as necessary when the web application undergoes changes.

By following these best practices, testers can create robust and maintainable automated tests using Selenium. Prioritizing unique, stable, and descriptive locators not only enhances test reliability but also improves overall testing efficiency.

Conclusion

Locators in Selenium are essential for effective automated testing, enabling precise interaction with web elements in a web application’s Document Object Model (DOM). Understanding the various locator types—such as ID, Name, Class Name, XPath, and CSS Selectors—allows testers to choose the most suitable strategies for their specific applications.

Following best practices, such as prioritizing unique identifiers and using stable locators, enhances the reliability and maintainability of test scripts. Additionally, implementing appropriate waiting mechanisms ensures tests run smoothly, even as web applications evolve.

Mastering locators in Selenium streamlines the testing process and contributes to delivering high-quality software that meets user expectations. Effective use of locators is key to ensuring accurate and efficient automated tests.

Test Locators in Selenium

Tags
Automation Testing Selenium