July 29, 2024

Selenium 4 – New Features with Examples

Selenium 4 marked a significant leap forward in test automation. Packed with new features and enhancements, this version revolutionized how testers approach web application testing. From improved browser compatibility to more efficient element identification, Selenium 4 offered a robust toolkit to streamline test development and execution. This article delves into the key features and their practical applications, showcasing the code improvements before and after Selenium 4.

List of Selenium 4 Features with Examples

W3C WebDriver Compliance

selenium 4.0 w3c compliance

Prior to Selenium 4, managing browser drivers for different browsers was a cumbersome task. Developers had to download the correct driver for each browser version, set the driver path in the code using system properties & maintain driver versions in sync with browser updates.

This manual process was error-prone and time-consuming, often leading to test failures due to incompatible driver versions. Selenium 4, in conjunction with WebDriverManager, streamlined this process significantly.

  • Automatic driver management: WebDriverManager automatically downloads and manages the correct driver version based on the specified browser.
  • Simplified code: The code becomes cleaner and more concise as you no longer need to explicitly set driver paths.
  • Reduced maintenance: WebDriverManager handles driver updates, ensuring compatibility with the latest browser versions.
// Before Selenium 4
WebDriver driver = new FirefoxDriver(); // Requires manual driver setup

// After Selenium 4 with WebDriverManager
WebDriver driver = new WebDriverManager.chromedriver().create(); // Automatic driver management

Relative Locators

selenium 4.0 relative locators

The code change introduced in Selenium 4 with relative locators addresses the issue of fragile locators. The original code relied on finding the search button using its id attribute:

This approach has a problem, which is “Fragility”. If the developer changes the HTML structure of the page and the “id” attribute of the search button is modified (e.g., renamed to “search-btn”), the test script will break because it can’t find the element anymore. After Selenium 4, the new code with relative locators introduces a more robust way to find the search results element:

//Before Selenium 4
WebElement searchButton = driver.findElement(By.id("search-button"));
//After Selenium 4 with relativeLocator
WebElement searchResults = driver.findElement(With.relativeLocator(With.below(searchButton)));

This approach offers several benefits:

  • Positional Dependence: Instead of relying on a specific attribute value (“search-button”), we define the search results element’s location relative to the search button. It describes that the search results element is found “below” the search button on the webpage.
  • Flexibility: Even if the HTML structure changes slightly, as long as the relative position of the elements remains the same (search results appear below the search button), the test script will still work. This makes the test more resilient to minor UI modifications.
  • Improved Readability: The code uses natural language (“below”) to describe the element’s location, making it easier for humans to understand the logic behind the test script.

WebElement Screenshot in Selenium 4

webelement screenshot in selenium 4.0

Before Selenium 4, capturing a screenshot of a specific web element involved capturing the entire webpage and then cropping the desired region using image processing techniques. This was a multi-step process that required additional code and processing time. Selenium 4 introduced a more direct and efficient way to capture screenshots of individual web elements. The primary change in Selenium 4 is the ability to directly capture a screenshot of a WebElement without the need for capturing the entire page and then cropping.

Before Selenium 4:

// Capture full page screenshot
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// Crop the image to the element's dimensions
BufferedImage elementImg = fullImg.getSubimage(location.getX(), location.getY(), width, height);

After Selenium 4:

// Capture element screenshot directly
File screenshot = element.getScreenshotAs(OutputType.FILE);

CDP for Advanced Interactions

chrome devtools in selenium 4.0

Before Selenium 4, WebDriver interactions were primarily limited to simulating user actions like clicks, typing, and navigation. While this was sufficient for many test scenarios, it lacked the ability to delve deeper into the browser’s functionality and environment.

Selenium 4 introduced a significant enhancement with the integration of the Chrome DevTools Protocol (CDP). CDP provides a comprehensive API for controlling and inspecting browsers, offering a vast array of capabilities that were previously inaccessible like Network Interactions, Browser Environment Manipulation, Debugging and Troubleshooting, Advanced Interactions, Security Testing etc.

Network Throttling with CDP

Imagine you want to test how your website works when the internet is slow. The following code helps you do that.

  • It makes your computer pretend to have a slow internet connection.
  • It then loads a website (like example.com) and checks how it behaves.
  • After testing, it makes the internet speed back to normal.
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v110.network.Network;   


public class NetworkThrottlingExample {
    public static void main(String[] args) {
        ChromeDriver driver = new ChromeDriver();
        DevTools devTools = driver.getDevTools();
        devTools.createSession();   


        // Enable the network domain
        devTools.send(Network.enable());

        // Configure network throttling (adjust parameters as needed)
        devTools.send(Network.emulateNetworkConditions(
            true, // offline
            0, // latency
            100 * 1024, // download throughput
            50 * 1024, // upload throughput
            10 * 1024 // downloadThroughput
        ));

        // Your test actions here...
        driver.get("https://www.example.com");

        // Disable network throttling
        devTools.send(Network.emulateNetworkConditions(
            false, // offline
            0, // latency
            0, // download throughput
            0, // upload throughput
            0 // downloadThroughput
        ));

        driver.quit();
    }
}

How CDP Helps:

  • Simulating real-world conditions: By controlling network conditions, you can test your application’s performance and behavior under various network scenarios, such as slow connections or offline environments.
  • Identifying performance bottlenecks: Analyzing network requests and response times can help pinpoint performance issues.
  • Intercepting and modifying network traffic: CDP allows you to intercept and modify network requests for testing purposes or to simulate specific scenarios.

Geolocation Emulation with CDP

This code is like telling your computer you are in a different place.

  • It makes your computer think you are in a specific city, like New York.
  • It then loads a website (like example.com) and sees if it shows information based on your new location.
  • After testing, it resets your location back to normal.
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v110.emulation.Emulation;

public   
 class GeolocationEmulationExample {
    public static void main(String[] args) {
        ChromeDriver driver = new ChromeDriver();
        DevTools devTools = driver.getDevTools();
        devTools.createSession();   


        // Enable the emulation domain
        devTools.send(Emulation.enable());

        // Set geolocation coordinates (adjust latitude and longitude)
        devTools.send(Emulation.setGeolocationOverride(
            40.7128, -74.0060, 10 // latitude, longitude, accuracy
        ));

        // Your test actions here...
        driver.get("https://www.example.com");

        // Clear geolocation override
        devTools.send(Emulation.clearGeolocationOverride());

        driver.quit();
    }
}

How CDP Helps:

  • Testing location-based features: You can verify that your application behaves correctly based on the user’s location.
  • Simulating different geographic regions: Test how your application handles different time zones, currencies, or language settings.
  • Improving test coverage: By covering various geolocation scenarios, you can increase the robustness of your test suite.

Conclusion

Selenium 4 is a big upgrade for anyone testing websites. It has new tools to help you find website parts easily, take pictures of them, and even change how the browser works. These improvements make testing faster and more accurate. It’s like having a supercharged toolbox for building better websites.

We’re excited about the possibilities Selenium 4 brings to the testing world. We’d love to hear your thoughts and experiences with this new version. Share your tips, tricks, or challenges in the comments below. Let’s build a strong testing community together!

You may also like