Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Do you know the difference between Implicit and Explicit Wait? If you need clarification and need to know when to use implicit or explicit Wait, you're at the right place. Implicit and explicit wait command is one of the essential commands in Selenium WebDriver testing. They dealt with web elements that take time to load on the webpage.
So let's start finding the difference between implicit and explicit Wait. But before that, You must Know about Selenium WebDriver.
What is Selenium WebDriver?
Selenium WebDriver is a web framework that can be used to automate testing. It has support for many languages, including Python and Java. It can simulate user interactions with web applications. It can fill out forms. It can click buttons, and it also can navigate between web pages.
To make use of it, we need to create a WebDriver instance. After that, navigate to the required web page and locate the relevant web element. Then we perform actions on the web element. Finally, we verify the generated output with the expected result.
Let us now have a look at what wait commands are.
What are Wait Commands?
While simulating user actions on a web application, we might face an “Element Not Visible Exception“ error. This error occurs because some elements need some time before appearing on the screen.
The selenium web driver may stimulate user action on the element even before the element is loaded. The Wait commands help us to deal with this issue. They pause the test execution for a certain period before moving to the next step.
Types of Wait Commands:
Implicit Wait
Explicit Wait
Fluent Wait
This article titled "Difference between Implicit and Explicit Wait" will discuss only Implicit and explicit Wait.
Implicit Wait
The implicit wait command helps us when a web page loads longer than expected.
It directs the Selenium WebDriver to stop the execution of the test script for a certain period before searching for each web element.
If the web element is found under the specified time, the required action will be taken.
If the element is not found, Selenium WebDriver will throw the “NoSuchElementException”.
We can use the implicit wait method using the following command:
Here, time is the period the Selenium WebDriver waits before throwing "NoSuchElementException".
Implementation in Java
import dev.failsafe.internal.util.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
public class SeleniumExamplesImplicitWait {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "path/to/geckodriver");
// create a new Chrome browser instance
WebDriver driver = new FirefoxDriver();
// set the implicit wait time to 10 seconds
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// navigate to the Github login page
driver.get("https://github.com/login");
// find the email input field and enter the email address
WebElement emailInput = driver.findElement(By.name("login"));
emailInput.sendKeys("example@email.com");
// find the password input field and enter the password
WebElement passwordInput = driver.findElement(By.name("password"));
passwordInput.sendKeys("password123");
// find the login button and click on it
WebElement loginButton = driver.findElement(By.name("commit"));
loginButton.click();
// close the browser
driver.quit();
}
}
Webdriver will move to the next statement if it is already on the screen. You can try to locate elements not present on the screen to see the WebDriver waiting and throwing an error!
Explicit Wait
The explicit wait command helps us when we need to wait for a specific event before moving to the next step.
In explicit Wait, we must define a condition and the maximum time to wait.
Once the condition is fulfilled, Selenium WebDriver moves to the next step.
If the condition is unmet, it will throw a 'TimeoutException’.
Following are the expected condition that can be used for waiting:
Condition
Description
alertIsPresent()
Check if an alert element is present on the screen or not.
elementSelectionStateToBe()
This can be used to check if the element is selected or not by passing parameter
elementToBeClickable()
This used to instruct a command to wait until the element is clickable by the locator.
elementToBeSelected()
This check if an element is selected.
frameToBeAvaliableAndSwitchToIt()
It checks if we can switch to the given frame.
invisibilityOfTheElementLocated()
Checks for if the element is either invisible or not present on the dom.
invisibilityOfElementWithText()
Checks for if the element with text is either invisible or not present on the dom.
presenceOfAllElementsLocatedBy()
Checks for availability of the all elements present on the webpage with given locator.
presenceOfElementLocated()
It is the expectation for checking that an element is present on the DOM of a page.
textToBePresentInElement()
Checks for presence of text in the element.
textToBePresentInElementLocated()
Checks for the given text in an element located by a locator.
textToBePresentInElementValue()
Check if the text appears in given element value attribute.
titleIs()
It checks the title of the webpage.
titleContains()
It checks for a case sensitive substring in the title of a webpage.
visibilityOf()
Whether an element that is present on the DOM is visible or not.
visibilityOfAllElements()
Check for visibility of all elements in the webpage that matches a given locator.
visibilityOfAllElementsLocatedBy()
Checks for visibility of all elements. Height and width should be greater than 0.
visibilityOfElementLocated()
Check for visibility of an element.it should be visible as well as height and width should be greater than 0.
We can use the Explicit wait condition in the following manner:
WebDriverWait Wait = new WebDriverWait(driver, time); // instancing a new wait object, wait for ‘time’ seconds.
wait.until(expectedCondtion);
Implementation in Java
import dev.failsafe.internal.util.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class SeleniumExamplesExplicitWait {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "path/to/geckodriver");
// create a new Chrome browser instance
WebDriver driver = new FirefoxDriver();
// navigate to the github login page
driver.get("https://github.com/login");
// find the email input field and enter the email address
WebElement emailInput = driver.findElement(By.name("login"));
emailInput.sendKeys("example@email.com");
// find the password input field and enter the password
WebElement passwordInput = driver.findElement(By.name("password"));
passwordInput.sendKeys("password123");
// set the explicit wait time to 10 seconds before login
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement welcomeMessage = wait.until(ExpectedConditions.presenceOfElementLocated(By.name("commit")));
// find the login button and click on it
WebElement loginButton = driver.findElement(By.name("commit"));
loginButton.click();
// close the browser
driver.quit();
}
}
As soon as the condition is resolved, webdriver will move to next statement. You can try different conditions to see webdriver actually waiting!
As we have discussed in brief about Implicit and Explicit wait commands. Let’s move to the next section, “Difference between Implicit and Explicit Wait”.
Difference between Implicit and Explicit Wait
The main difference between implicit and explicit Wait is that implicit Wait does not depend upon any condition. It waits for every element before searching for it. The explicit Wait depends on the condition and moves to the next step as soon as the condition is fulfilled without wasting time.
Following are the differences between Implicit and Explicit Wait:
Parameters
Implicit
Explicit
Scope
It is applied to all elements globally. Selenium WebDriver waits before searching for each element.
It is applied to a particular element or a group of elements. It is based on condition.
Waiting Strategy
Implicit Wait waits before the element appears.
The explicit Wait can wait for many different conditions, such as the clickability of an element, etc.
Behavior
Implicit Wait throws "NoSuchElementException" when the element does not appear even after the timeout.
Explicit Wait throws "TimeoutException" if the condition is not met in the specified time.
Flexibility
Implicit has limited flexibility in waiting types
Offers various waiting conditions
Customization
Implicit hascustomization options
Highly customizable and adaptable
Use case
For static or predictable elements
For dynamic or conditional scenarios
Handling State elements
Does not handle stale elements well, may lead to issues if the DOM changes frequently
Handles stale elements effectively by rechecking conditions when necessary, reducing errors in dynamic pages
An implicit wait is static in nature. It is set once at the beginning of the test script and remains constant throughout the script's execution, waiting a fixed amount of time before interacting with elements.
What are the advantages of using Selenium WebDriver-based automated testing?
Selenium WebDriver supports multiple languages like Java, Python, and Ruby. It can be used to do cross-browser testing. It is an open-source framework and has a vast community.
What is Fluent Wait?
Fluent Waut checks for the web element on the screen repeatedly for a certain period of time. Users have to define the time after which the driver will check for web elements on the screen.
Which wait is better in Selenium?
Explicit Wait is often considered better because it offers more control and flexibility and is suitable for handling dynamic elements and waiting for specific conditions, making tests more robust and efficient.
Can we use implicit and explicit wait together?
Yes, you can use implicit and explicit waits together in Selenium. However, it's generally discouraged because it can lead to unpredictable wait times and unexpected behavior. It's better to use explicit waits for specific conditions and elements.
Conclusion
Selenium Webdriver is used to automate the testing. It is also used for cross-browser testing. Some elements take time to load on the screen. If we execute the test script, such an element may lead to Element Not Visible Exception. We can use the Wait command in such cases. The difference between Implicit and Explicit Wait is that Implicit Wait waits for every element before looking for it, while Explicit Wait waits only as per the specified conditions.
Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.