Unleashing the Power of Selenium 4: A Deep Dive into Relative Locators

Unleashing the Power of Selenium 4: A Deep Dive into Relative Locators

With the launch of Selenium 4, it has introduced some new features and improvements over the Selenium 3. One of these features is the relative locators, which are also known as friendly locators.

What are Relative Locators?

Relative locators are a new way of locating web elements on a web page based on their spatial relationship with other web elements. They are useful when it is difficult to construct a locator for the desired element, but easy to describe where the element is in relation to another element that has an easily constructed locator.

Selenium 4 leverages the JavaScript function getBoundingClientRect() to precisely determine the size and position of web elements on a page. This information is then utilized to locate neighboring elements with accuracy, marking a significant enhancement in the capabilities of Selenium for web automation.

For example, suppose you want to locate the checkbox for the newsletter option on a web page. The checkbox does not have an id, name, or class attribute, so you cannot use the traditional locators such as id, name, or class name. However, you can see that the checkbox is near the label that says “Newsletter:”, which has an id of “newsletter”. In this case, you can use the relative locator near() to locate the checkbox as the element that is near the element with id “newsletter”.

Relative locators are not meant to replace the traditional locators, but to complement them and provide more flexibility and readability for locating web elements.

How to Use Relative Locators?

Selenium 4 provides five relative locators that can be used to locate web elements based on their position with respect to other web elements. These are:

  • above(): locates the element(s) that are above the specified element
  • below(): locates the element(s) that are below the specified element
  • toLeftOf(): locates the element(s) that are to the left of the specified element
  • toRightOf() : locates the element(s) that are to the right of the specified element
  • near(): locates the element(s) that are near the specified element, within a certain distance (default is 50 pixels)

The syntax for using relative locators is similar to using the traditional locators. You need to pass the relative locator as an argument to the findElement() or findElements() methods of the WebDriver object. You can also chain multiple relative locators together to narrow down the search.

For example, to locate the element that is below and to the left of the element with some ids, you can write:

WebElement element = driver.findElement(RelativeLocator.with
                    (By.tagName("div")).toLeftOf(By.id("p6"))
                    .below(By.id("p2")));

To locate the elements that are near the element with id “bar”, within 100 pixels, you can write:

WebElement elements = driver.findElements(
    RelativeLocator.with(By.tagName("div"))
    .near(By.id("bar"), 100));

Why Use Relative Locators?

Relative locators have some advantages over the traditional locators, such as:

  • They are more readable and intuitive, as they describe the web elements in a natural language
  • They are more resilient to changes in the web page layout, as they do not depend on the exact attributes or positions of the web elements
  • They can locate web elements that are otherwise difficult or impossible to locate using the traditional locators, such as elements that do not have any unique attributes or elements that are dynamically generated

Code Examples

To demonstrate how to use relative locators in practice, let us use the reference from https://qaclub.online/products as an example. It contains a simple gallery like products layout which will help us understand relative locators better.

Let us write some tests in Java to locate some of the web elements on this web page using relative locators.

To use relative locators in Java, you need to import the following package:

import org.openqa.selenium.support.locators.RelativeLocator;

You can also use the static import to avoid writing the class name every time:

import static org.openqa.selenium.support.locators.RelativeLocator.with;

Here are some examples of using relative locators in Java:

@Test
    public void testLeftBelowRelativeLocators() {

        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("p6")));

        String id = driver.findElement(RelativeLocator.with(By.tagName("div"))
                .toLeftOf(By.id("p6")).below(By.id("p2")))
                .getAttribute("id");
        System.out.println("ID= " + id);

        assertEquals(id, "p5");
    }

    @Test
    public void testRightAboveRelativeLocators() {

        String id2 = driver.findElement(RelativeLocator.with(By.tagName("div"))
                .toRightOf(By.id("p2")).above(By.id("p6")))
                .getAttribute("id");
        System.out.println("ID2= " + id2);

        assertEquals(id2, "p3");
    }

    @Test
    public void testNearPixelsRelativeLocators() {

        String id3 = driver.findElement(RelativeLocator.with(By.tagName("div"))
                .near(By.id("p9"), 100))
                .getAttribute("id");
        System.out.println("ID3= " + id3);

        assertEquals(id3, "p6");
    }

You can find the full example in the QA Club GitHub here.

Conclusion

Relative locators are a new feature in Selenium 4 that allow us to locate web elements based on their spatial relationship with other web elements. They are more readable, resilient, and flexible than the traditional locators, and can help us deal with complex or dynamic web pages.

If you want to learn more about Selenium 4 and test automation, you should join the QA Club, a new community platform dedicated to test automation. QA Club is a place where you can find tutorials, tips, and best practices on test automation, as well as connect with other testers and developers who share your passion. You can also ask questions, share your experiences, and get feedback from the experts.

Don’t miss this opportunity to join the QA Club – your gateway to mastering the art of test automation and become a part of the test automation community. Join now and start learning and sharing with the best. 😊