Web Locators In Selenium

Web locators are an essential component of every Selenium script when it comes to Automation Testing. Web locators enable you to locate certain items on a web page and interact with them, such as clicking a button or filling out a form. But, selecting the best web locator may be difficult, especially when working with dynamic websites.

This blog article will give a full reference to Selenium web locators, including an overview of the many types of web locators as well as recommended practises for selecting and optimising them. At the conclusion of this post, you will have mastered web locators and improved the stability and dependability of your Selenium scripts. Let’s get started!

Understanding Web Locators

Web locators in Selenium are used to locate and interact with elements on a web page. They are essential tools that allow you to locate particular elements on a page, such as text fields, buttons, links, etc. Selenium provides a range of different web locators that you can use to find and interact with elements on a web page.

Here are some of the most common types of web locators:

  • ID Selector:
    An ID is a unique identifier for a web page element. Although IDs are often the simplest and most reliable way of finding an element, not all items have an ID.
    Syntax:
driver.findElement(By.id("elementID"));
  • Class Name Selector:
    A class name is a way to group multiple elements on a web page. Class names are useful when you need to locate multiple elements that share similar attributes.
    Syntax:
driver.findElements(By.className("className"));
  • Name Selector:
    A name is a way to identify an element by a specific name attribute. Name attributes are commonly used with form elements.
    Syntax:
driver.findElement(By.name("nameAttribute"));
  • Tag Name Selector:
    A tag name is the name of the HTML tag that defines an element. Tag names can be used to locate multiple elements that share the same tag name.
    Syntax:
driver.findElements(By.tagName("tagName"));
  • Link Text Selector:
    Link text is used to locate hyperlinks on a web page.
    Syntax:
driver.findElement(By.linkText("linkText"));
  • Partial Link Text Selector:
    Partial link text is similar to link text, but it allows you to locate a hyperlink based on a partial match of the link text.
    Syntax:
driver.findElement(By.partialLinkText("partialLinkText"));
  • CSS Selector:
    A CSS selector is a pattern that matches elements based on their attributes. CSS selectors offer a lot of flexibility and can be used to locate elements with complex structures.
    Syntax:
driver.findElement(By.cssSelector("CSSSelector"));
  • XPath Selector:
    XPath is a language that allows you to navigate the structure of an XML or HTML document. XPath can be used to locate elements based on their attributes or their position in the document.
    Syntax:
driver.findElement(By.xpath("XPathExpression"));

Putting Everything Together in Practical Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;

public class LocatorExample {
    public static void main(String[] args) {
     
        // create a new instance of the Chrome driver
        WebDriver driver = new ChromeDriver();

        // navigate to the test website
        driver.get("https://example.com");

        // find elements by ID selector
        driver.findElement(By.id("username"));
        driver.findElement(By.id("password"));

        // find elements by name selector
        driver.findElement(By.name("submit"));

        // find elements by class name selector
        driver.findElements(By.className("button"));

        // find elements by tag name selector
        driver.findElements(By.tagName("a"));

        // find elements by link text selector
        driver.findElement(By.linkText("About Us"));

        // find elements by partial link text selector
        driver.findElement(By.partialLinkText("Sign In"));

        // find elements by CSS selector
        driver.findElement(By.cssSelector("#login-button"));

        // find elements by XPath selector
        driver.findElement(By.xpath("//input[@name='email']"));

        // close the browser
        driver.quit();
    }
}

Best Practices For Choosing Web Locators

When it comes to choosing the right web locator, there are several best practices that you should keep in mind. Here are some key factors to consider:

  • Uniqueness:
    Choose a locator that is unique to the element you want to interact with. If your locator matches multiple elements, your script may interact with the wrong element, which can cause errors or unexpected behavior.
  • Stability:
    Choose a locator that is stable and unlikely to change over time. If your locator changes, your script will no longer be able to locate the element, which can cause your script to fail.
  • Readability:
    Choose a locator that is easy to read and understand. This can help make your code more maintainable and easier to update in the future.
  • Performance:
    Choose a locator that is efficient and fast. Slow or inefficient locators can slow down your test execution and increase the time it takes to run your tests.

To illustrate these best practices, let’s look at some examples of good and bad web locators:

Good Example:

<input id="email" name="email" class="form-control">

This locator uses the “id” attribute, which is unique and stable, and also includes the “name” and “class” attributes for readability and maintainability.

Bad Example:

<div class="content">

This locator uses a “class” attribute, but it is not unique and matches multiple elements on the page. It also lacks specificity, making it difficult to understand and maintain.

Strategies For Finding Web Locators

Finding the right web locator can sometimes be challenging, especially for more complex web applications. Here are some strategies you can use to help you find the best web locator for your needs:

  • Inspect the Element:
    Most web browsers have a built-in tool that allows you to inspect the HTML code for any element on a web page. This tool can help you identify the attributes and properties of the element you want to interact with, which you can then use to create a web locator.
  • Use Relative Locators:
    Relative locators allow you to identify elements based on their relationship to other elements on the page. For example, you can use a relative locator to identify the “Submit” button that is next to a particular form field.
import net.serenitybdd.core.annotations.findby.By;
import net.serenitybdd.screenplay.targets.Target;

// define the target for the email field
Target emailField = Target.the("email field").located(By.id("email-field"));
                          
// define the target for the submit button near the email field
Target submitButton = Target.the("submit button").located(By.xpath(".//input[@type='submit']").near(emailField));

// click the submit button
submitButton.click();
  • Use Regular Expressions:
    Regular expressions can be a powerful tool for finding web locators that match specific patterns or formats. For example, you can use a regular expression to find all email input fields on a page.
List<WebElement> emailFields = driver.findElements(By.cssSelector("input[type*='email']"));
  • Use Dynamic Locators:
    Dynamic locators are locators that change dynamically based on the state of the web page. For example, you can use a dynamic locator to identify the “Submit” button that only appears after a certain form field has been filled out.
WebElement inputField = driver.findElement(By.id("my-input-field"));

// enter some text in the input field
inputField.sendKeys("some text");

// use a dynamic locator to locate the "Submit" button
By submitBtnLocator = By.cssSelector("input[id*='submitBtn'][disabled!='disabled']");

// wait for the "Submit" button to become visible
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement submitBtn = wait.until(ExpectedConditions.visibilityOfElementLocated(submitBtnLocator));

// click the "Submit" button to submit the form
submitBtn.click();
  • Use Waiting Strategies:
    Sometimes web pages can take longer to load or render, which can cause your script to fail if it tries to interact with an element before it is available. Waiting strategies like implicit and explicit waits can help ensure that your script waits until the element is available before interacting with it.
// implicit wait of 10 seconds
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// explicit wait of 10 seconds
WebDriverWait wait = new WebDriverWait(driver, 10);

Tips For Optimizing Web Locators

Optimizing your web locators can help improve the performance and reliability of your test scripts. Here are some tips for optimizing your web locators:

  • Use the Right Selector:
    When choosing a web locator, make sure you use the most efficient selector possible. For example, using an “id” selector is generally faster than using a “class” selector.
  • Avoid Lengthy XPath Expressions:
    XPath expressions can be powerful, but they can also be lengthy and slow to execute. Whenever possible, try to use simpler locators like “id” or “name”.
  • Use CSS Selectors:
    CSS selectors can be a faster and more efficient way to locate elements than XPath. They are also easier to read and understand, which can help make your code more maintainable.
  • Keep Your Selectors Simple:
    Avoid creating overly complex selectors with multiple attributes or pseudo-classes. Instead, try to keep your selectors simple and specific.
  • Use Custom Attributes:
    If the attributes on your element are not unique or stable enough to use as a locator, consider adding a custom attribute to the element that you can use as a locator.

Console For Verifying Web Locators

You can verify a web locator using the browser’s console in the following way:

  1. Open the webpage in your browser.
  2. Open the browser’s developer tools by pressing F12 or right-clicking on the page and selecting “Inspect”.
  3. In the developer tools, select the “Console” tab.
  4. Type the JavaScript code that uses the locator in the console, and press Enter.
  5. The console should output the element that matches the locator.

For example, to use the document.querySelector() method to find an element using a CSS selector, you can type the following code in the console:

document.querySelector("input[type='password']")
queryselector - testingmint.com

This will output the first input element with the name attribute equal to “Password”. You can then use this selector in your Selenium tests to locate the element.

Mostly Used Browser Extension For Web Locators

If you don’t want to verify web locators manually, then you can use the following tools:

  • SelectorsHub:
    SelectorsHub is a browser extension that can help you find and generate CSS and XPath selectors for web elements on a webpage. It also provides a range of features that can simplify web automation tasks, such as text manipulation and date/time calculations.
  • ChroPath:
    ChroPath is a browser extension that provides a simple and easy-to-use interface for generating XPath and CSS selectors for web elements on a webpage. It allows you to quickly and easily copy selectors to your clipboard, making it easy to use them in your automation scripts.
  • XPath Helper:
    XPath Helper is a browser extension that can help you to create, test, and evaluate XPath expressions. You can highlight an element on the page and generate an XPath expression that locates it. XPath Helper also provides a range of other features for working with XPath, such as evaluating expressions and editing XML documents.
  • Truepath:
    Truepath is a browser extension that can help you find and generate XPath selectors for web elements on a webpage. It provides a range of features for simplifying web automation tasks, such as copying element attributes and generating test data.
  • Xpath finder:
    Xpath finder is a browser extension that can help you locate web elements on a webpage using XPath expressions. It allows you to highlight elements on the page and generate XPath expressions that can be used to locate them. Xpath finder also provides a range of other features for working with XPath, such as evaluating expressions and generating test data.

All of these tools provide a simple and easy way to find and generate web locators for automating web tasks using Selenium or other web automation frameworks. Depending on your needs and preferences, you can choose the tool that suits you the best.

Conclusion

Web locators are a critical component of automated web testing with Selenium. By using the right locator strategy, you can create more reliable and maintainable test scripts that can help you catch bugs and ensure the quality of your web applications.
In this article, we’ve covered some best practices and tips for choosing, finding, and optimizing web locators, as well as some browser tools you can use to make the process easier. By following these guidelines, you can help ensure that your test scripts are as efficient and effective as possible, which can save you time and improve the overall quality of your software.
Remember to always choose the most efficient and specific locator possible, keep your locators simple, and use the right tools to make the process easier. By doing so, you can build more reliable and robust test automation suites that can help you deliver better software to your users.