Skip to main content

Upgrading to Selenium 4 for Sauce Labs Testing

This doc will guide you through how to upgrade to Selenium 4, which has just been released!

Although Selenium 4 is designed to be a straightforward drop-in replacement, you'll need to be aware of the new and deprecated features that may impact your Sauce Labs automated tests. This is especially important if you've built custom functionalities in your testing framework.

What You'll Learn#

  • Tips for adjusting your tests and dependencies.
  • How to prevent and resolve potential issues that could arise during your Selenium upgrade.

What You’ll Need#

  • A Sauce Labs account (Log in or sign up for a free trial license).
  • A working development environment for one of the supported Selenium languages: Java, C#, Python, or Ruby. Although Selenium has JavaScript bindings, we recommend using WebdriverIO when running tests on Sauce Labs.
  • Strongly recommended: use one of the programming languages officially supported by Selenium 4 (Java, JavaScript, Python, Ruby, or C#).

W3C WebDriver-Compliant Sessions#

Selenium 4 deprecates support for legacy JSON Wire Protocol (JWP). As part of this change, Selenium is moving away from the less structured Desired Capabilities classes to Browser Options classes.

  • Facilitates creation of W3C-Compliant WebDriver Capabilities.
  • Simplifies the configuration needed to start a new session.
  • Allows you to set both defined W3C Capabilities, and browser-specific settings.
  • Reduces the chances of browser misconfiguration.

W3C-Defined WebDriver Capabilities#

Here's a list of W3C WebDriver capabilities applicable to Sauce Labs:

  • browserName
  • browserVersion
  • platformName
  • acceptInsecureCerts
  • pageLoadStrategy
  • proxy
  • timeouts
  • unhandledPromptBehavior

Any capability not in this list must include a vendor prefix. This rule applies to browser-specific capabilities as well as Sauce Labs-specific capabilities.

So, Firefox specific capabilities need to be nested inside a moz:firefoxOptions or other moz:XXX keys. If you use a Browser Options class this is all handled for you. For Sauce Labs, though, we need you to create a Hash or Dictionary of Sauce Labs specific settings and place it inside a sauce:options object. See the examples in the next section.

Converting from Capabilities to Options#

To customize your default settings, check out the new Selenium 4 tab on the Sauce Labs platform configurator. All the valid sauce:options parameters are described on the Test Configurations page.

Deprecated Code
DesiredCapabilities caps = DesiredCapabilities.firefox();caps.setCapability("platform", "Windows 10");caps.setCapability("version", "92");caps.setCapability("build", myTestBuild);caps.setCapability("name", myTestName);WebDriver driver = new RemoteWebDriver(new URL(sauceUrl), caps);
Recommended Code
loading...

Remote WebDriverBuilder#

Java only

An alternate way to start your session in Java is with the RemoteWebDriverBuilder. This class has a few advantages for Sauce Labs users, including automatic driver augmentation (driver augmentation is required for several of the new features below), and the ability to set HTTP Client settings like read timeouts.

Click here to see an example of using the RemoteWebDriverBuilder.
RemoteWebDriverBuilder
loading...

New Features#

Here are 10 new features in Selenium 4 that you can use in your Sauce Labs tests, with code examples in each programming language.

1. Relative Locators#

Relative locators allow you to identify elements in relationship to each other as they are displayed on the page using more natural, language friendly terms, such as “above”, “below”, “left of”, “right of”, and “near”.

caution

Changing the size of browser window or adding or removing things on the page can change which element is located.

Relative Locators
loading...

2. New Window#

Create and Switch to a new (blank) tab or window.

Create New Window
loading...
Create New Tab
loading...

3. Print Page#

The ability to print a page as a PDF in Chrome, Firefox and Edge. There are quite a few customizations that can be made including page size, range, margins, background, and shrink to fit. Here are code examples with the defaults:

note

For Chrome and Edge, this only works in Headless mode.

Print Page
loading...

4. Element Attribute vs Property#

The Selenium 3 method for getting an element's attribute does not actually give you the element's attribute. Because most people don't know the difference between an element and an attribute, Selenium created a way to provide the user with whichever value they probably wanted. Because this magic can not be precisely specified for the W3C, two new methods were created. The original method hasn't changed, but using it will be slightly less performant on Sauce Labs, as well as less precise. The new methods are named slightly differently in each language.:

Click here to see multiple examples of the behavior of these attribute and property methods.
Attributes vs Properties
loading...

5. Chromium Edge Options#

When the latest version of Selenium 3 was released, Microsoft Edge was still implemented with the now deprecated EdgeHTML browser engine. So none of the custom options for working with the Chromium version of Edge were available in Selenium 3.

Chromium Edge Options
loading...

6. Timeout Getters#

This is a long requested feature. Selenium 3 allowed you to set timeouts whenever you liked, but provided no way to query the driver for the current timeout values. Selenium 4 provides that ability now.

tip

Best practice is to set the timeout values in the Options class when starting the session and then ignore them during the test (do not use the setters or getters).

Get Timeouts
loading...

7. Network Conditions#

Chrome and Edge only

Selenium 4 provides a set of parameters to modify network conditions, such as:

  • Going offline
  • Setting a latency for the connection
  • Altering the upload or download throughput.

This can be useful to test web applications under different network conditions.

note

Since 2017, we've provided the ability to throttle network settings through our Extended Debugging feature.

Network Conditions
loading...

8. Full Page Screenshots#

Firefox only

Features like "infinite scroll" makes it impossible to explicitly define what a "full page" entails for a W3C specification. As such, the default screenshot method in Selenium 3 only returns what is visible in the Viewport. Mozilla implemented a separate method to allow for a full page screenshot.

Full Page Screenshot
loading...

9. Install and Uninstall Addons#

Firefox only

All the other browsers drivers allow you to install extensions with the Browser Options class. Firefox requires a separate method after the browser has been started.

Install and Uninstall Addons
loading...

10. Change Preferences During Session#

Firefox only

In Selenium 3, you can only set preferences in the Capabilities at the beginning of a test. Firefox has provided a way in Selenium 4 to update things whenever you want during a session. This is done by toggling the context between "chrome" and "content".

Here are some examples of using the "chrome" context to change the default accepted language of the browser:

caution

Most Selenium commands are not valid in the "chrome" context, so make sure you switch back after using it.

Change Context
loading...
Bidirectional APIs

We support all new Selenium 4 features except for Bidirectional APIs. While we're working hard to add full support, we do provide similar functionality through our Extended Debugging feature, which allows you to:

  • Intercept network requests to mock backends
  • Throttling performance of both network and CPU
  • Access console and network logs

Upgrading Your Dependencies#

Selenium 4 has been released! Check the sections below to install Selenium 4 and have your project dependencies upgraded.

The process of upgrading Selenium depends on which build tool is being used. We will cover the most common ones for Java — Maven and Gradle — plus JavaScript, Python, Ruby, and C#.

Minimum Java version required is still 8.

Selenium 3 Dependency
loading...
Selenium 4 Dependency
loading...

After making the change, you could execute mvn clean compile on the same directory where the pom.xml file is.

Potential Errors and Deprecation Messages#

Below are code examples that can help resolve deprecation messages you might encounter after upgrading to Selenium 4.

Find Element(s) Utility Methods#

Java only

FindsBy interfaces, utility methods to find elements in the Java bindings, have been removed, as they were meant for internal use only. In Example 2, you'll see that all the findElements* have been removed as well.

Example 1

driver.findElement(By.className("className"));driver.findElement(By.cssSelector(".className"));driver.findElement(By.id("elementId"));driver.findElement(By.linkText("linkText"));driver.findElement(By.name("elementName"));driver.findElement(By.partialLinkText("partialText"));driver.findElement(By.tagName("elementTagName"));driver.findElement(By.xpath("xPath"));

Example 2

driver.findElements(By.className("className"));driver.findElements(By.cssSelector(".className"));driver.findElements(By.id("elementId"));driver.findElements(By.linkText("linkText"));driver.findElements(By.name("elementName"));driver.findElements(By.partialLinkText("partialText"));driver.findElements(By.tagName("elementTagName"));driver.findElements(By.xpath("xPath"));

Timeout Parameters#

Java only

The parameters received in Timeout have switched from expecting (long time, TimeUnit unit) to expect (Duration duration).

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));driver.manage().timeouts().scriptTimeout(Duration.ofMinutes(2));driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));

Wait Parameters#

Waits are also expecting different parameters now. WebDriverWait is now expecting a Duration instead of a long for timeout in seconds and milliseconds. The withTimeout and pollingEvery utility methods from FluentWait have switched from expecting (long time, TimeUnit unit) to expect (Duration duration).

new WebDriverWait(driver, Duration.ofSeconds(3)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("#id")));
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)  .withTimeout(Duration.ofSeconds(30))  .pollingEvery(Duration.ofSeconds(5))  .ignoring(NoSuchElementException.class);

Merging Capabilities#

Prior to Selenium 4, you could merge one set of capabilities into different set, and this would mutate the calling object. With Selenium 4, this is deprecated; you'll need to manually assign the result of the merge operation.

MutableCapabilities capabilities = new MutableCapabilities();capabilities.setCapability("platformVersion", "Windows 10");FirefoxOptions options = new FirefoxOptions();options.setHeadless(true);options = options.merge(capabilities);

The result of the merge call needs to be assigned to an object.

Firefox Legacy#

Before GeckoDriver was around, the Selenium project had a driver implementation to automate Firefox versions below 48. With the release of Selenium 4, this implementation is not needed anymore, as it does not work in recent versions of Firefox.

To avoid major issues when upgrading to Selenium 4, the setLegacy option will be shown as deprecated. We recommend relying only on GeckoDriver, rather than using the old implementation. The following code will show the setLegacy line deprecated after upgrading.

FirefoxOptions options = new FirefoxOptions();options.setLegacy(true);

Browser Interface#

With Selenium 4, the BrowserType interface will be deprecated and replaced by the new Browser interface.

MutableCapabilities capabilities = new MutableCapabilities();capabilities.setCapability("browserVersion", "92");capabilities.setCapability("browserName", Browser.FIREFOX);

AddAdditionalOption#

C# only

The AddAdditionalCapability capability is deprecated in Selenium 4. Instead of it, AddAdditionalOption is recommended.

var browserOptions = new ChromeOptions();browserOptions.PlatformName = "Windows 10";browserOptions.BrowserVersion = "latest";var sauceOptions = new Dictionary<string, object>();browserOptions.AddAdditionalOption("sauce:options", sauceOptions);

More Information#

Comprehensive Guide to S4#

See Sauce Labs | A Comprehensive Guide to Selenium 4.

Frequently Asked Questions#

See Frequently Asked Questions About Selenium 4.

Related Resources#