Selenium

Explicit Waits in Selenium

Selenium offers waits to solve the synchronization issues. In this article, we will discuss the Explicit Wait method. The explicit method holds the execution of the next step until it finds the element in a given specific time. In this content, we will have an overview about the Selenium waits and understand the advantages of Explicit Wait. This article implements a basic example of Explicit Waits and uses try-and-catch blocks to catch the exception.

What Are the Waits in the Selenium Framework?

Selenium waits help to solve the synchronization problems. The synchronization is the process of matching the “test automation tool speed” with the speed of “website under test”. In this process, the WebDriver executes a certain task on the webpage but the WebElement is not loaded in “website under test”. In this situation, the WebDriver throws a “NoSuchElementExpection” or “ElementNotVisibleExpection” exceptions. There are three types of waits method which are provided by the Selenium framework.

Implicit Wait

This type of wait applies to all website elements that’s why it is called a global wait. The implicitlyWait() method is used to call it.

Explicit Wait

It is a webelement specific wait type. It waits for a certain time to load the specific element before throwing an exception.

Fluent Wait

It gives the maximum amount of time to find the WebElement.

What Is an Explicit Wait in Selenium?

The explicit wait type is different from the Implicit wait. This wait method holds for a certain time until a specific condition occurs before proceeding to the next line of code. It is helpful where some elements load faster and some elements load slower. For example: There are two or three elements that take 20 to 30 seconds to load on the web page. Here, you can’t go and change the wait according to the maximum time which is taken by one of the WebElement. That’s where the Explicit Wait plays its part. Explicit Wait specifies the wait for that particular element on the web page. You can specify to wait for a particular element for a long time; that’s where we use the Explicit Wait. The WebDriverWait method is used to call the EExplicit Wait.

Selenium WebBrowser Interface

The WebDriver interface enables the automation test implementation. The WebDriver is used to control and create interaction between website and Selenium automation tools like finding the elements, navigating the URLs, obtaining attribute properties, confirming if the text is there in the WebElement, searching for an element, and more.

You can utilize a variety of web browsers including Firefox, Safari, and Chrome. Every type of browser has a specific class for that type of browser such as FirefoxDriver, ChromeDriver, InternetExplorerDriver, etc. All browsers can be implemented through the WebDriver method.

Here is the syntax for using the WebDriver interface:

from selenium import webdriver

driver = webdriver.Chrome()

driver.get('https://www.ebay.com')

In the provided chunk of code, we create the “driver” object of the WebDriver. Here, we use the Chrome browser with the method.Chrome() class. After that, the browser launches and opens the given URL.

Example 1:

In this first program, a very basic Explicit wait example is implemented which is very useful for beginners and experienced developers.

There are scenarios where we first find the “Daily Deals” WebElement and navigate to the Daily Deals page. If the condition is true, print the “Condition True”. Otherwise, print the “Condition False” exception.

First, we import all necessary libraries of Selenium and WebBrowser. To use the Explicit wait, import the following libraries:

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

We provide the complete code in the following:

package ui;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Explicit_wait {
    public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver","C:\\browserdrivers\\chromedriver.exe");
        ChromeDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.ebay.com/");
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        try {
            WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Daily Deals")));
            element.click();
            System.out.println("condition True");
        }
        catch(Exception e)
        {
            System.out.println(e);
            System.out.println("condition False");
        }
        driver.quit();
    }
}

Now, let’s understand the previous code step-by-step and explain what actions each line performs.

In the first chunk of code, we get the browser libraries from the machine and then launch the Chrome browser drivers.

In this example, we use the Chrome browser. The following syntax is used to implement it:

System.setProperty("webdriver.chrome.driver","C:\\browserdrivers\\chromedriver.exe");

ChromeDriver driver = new ChromeDriver();

After that, we maximize the browser window and open the given website using the following given syntax:

driver.manage().window().maximize();

driver.get("https://www.ebay.com/");

For this example, we use the eBay website located at https://www.ebay.com/.

s

If we want to verify whether the “Daily Deal” Hyper-line exists or not, we should know where the “Daily Deal” is present on the website. To find the LinkText locator of the “Daily Deals” hyper-line, we need to inspect the “Daily Deals” particular on the web page and find the <a></a> tag innertext. The screenshot is attached in the following to see where we can find the “Daily Deals” <a> tag.

find

In the previous screenshot, we see that <a> tag for “Daily Deals” is present on the web page. If there is no present <a> tag, there is no present “Daily Deals” hyper-line. We need to use this following hint:

driver.findElement(By.LocatorType(“LocatorValue”));

We use the driver.findElements() method to check if an element is present on a webpage or not. The “By” object is a parameter for the Find Element command which delivers an object of the WebElement type. The various locator techniques such as Name, ID, ClassName, XPath, etc. link text can be used with the “By” object. As we are aware, a list of WebElements that are located using the “By Locator” parameter is returned by the findElements() function. If the element is found, a list of non-zero WebElements is returned. Otherwise, a list of size 0 is returned. As a result, the length of the list can be utilized to determine if an entry is present or not.

For this example, we use the LinkText locator as shown in the following syntax:

driver.findElement(By.linkText("Daily Deals")).click();

In the previous code chunk, find the “Daily Deals” hyper-line text first. After that, use the click() function to navigate to another page.

After that, the Explicit wait is implemented in the following given syntax:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

When we use the previous chunk of code for the Explicit wait, keep in mind that the function waits for 10 seconds as defined in the webDriverWait method until the given locator is found.

The webDriverWait method is used to implement explicitly. Create the “wait” reference object of the webDriverWait class. Then, allocate the memory with the new WebDriverWait and pass two parameter (1) Web driver’s reference object and mentioned (2) Time duration (driver, Duration.ofSeconds(10)).

Now, use the reference object of the webDriverWait class which is “wait” to call the until() method and pass the expected visibilityOfElementLocated(By.id) condition. If the expected condition is true, return the WebElement and wait for 10 seconds until this condition comes true. This expected condition is the WebElement specification. Here, we have to wait for the “element” visibility. If the element is visible within 5 seconds, wait exits. If not, it maximizes the wait for 10 seconds.

Here is the given syntax for the expected condition:

Wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“element”)));

There are many expected conditions which are provided by Selenium such as alertIsPresent(), elementSelectionStateToBe(), elementToBeClickable(), etc. Here in this tutorial, we use the “VisiblityOfElementLocated()” condition.

Let’s move to the next chunk of code where we have the “Condition True”:

try {
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Daily Deals")));
            element.click();
            System.out.println("condition True");
        }
        catch(Exception e)
        {
            System.out.println(e);
            System.out.println("condition False");
        }

To check if the element exists or not, we use a try and catch block. All we need to do is try to find the element and interact with it.

WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Daily Deals")));

element.click();

System.out.println("condition True");

Wait for the element with the “Daily Deals” linkText. If we find the WebElement, click that element to navigate to another page and print the “Condition True” in the console.

Here in the following output screenshot, we can see that the element find is successful. Navigate the page:

succes

clickweb

Let’s move to the next chunk of code where we have the “Condition False”:

try {
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Wrong Element")));
            element.click();
            System.out.println("condition True");
        }
        catch(Exception e)
        {
            System.out.println(e);
            System.out.println("condition False");
        }

If the “Wrong Element” hyper-line text is not present on the web page, throw the exception and print the “Condition False” output in the console.

In the following output screenshot, we can see that the element is found unsuccessful:

error

Finally, after executing all the code, close the browser using the quit() method.

driver.quit();

Conclusion

You now learned about Selenium Explicit Wait advantages. You will learn how to implement it in a real scenario. This article implements the example where you hold the execution of further code until you find the element on a given wait time. This article contains the try and catch conditions. If the element is exiting, print the “Condition True”. Otherwise, print the “Condition False”.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content