Using Explicit Wait As WebDriverWait in Selenium WebDriver

Prerequisite posts :-

Using Thread.sleep() in Selenium WebDriver

Using Implicit Wait in Selenium WebDriver

Let’s continue exploring Explicit wait in Selenium WebDriver now.

As of now we know two wait mechanisms which we can use in Selenium WebDriver. Sleep just makes current thread idle for specified time and implicit wait just works for location web elements. But are these enough or can cover all scenarios where we need to wait?

  1. What if I need to wait till title of page is something?
  2. What if I need to wait for invisibility of a web element?
  3. What if I need to wait till desired row is visible in a table?
  4. What if I need to wait till some specific operations are completed?
  5. What if I need to wait enable or disability of a web element?

Let’s see some scenarios in detailed below :-

  1. A text box appears when user clicks on a Login button with little delay. In beginning text box is disable but gets enable automatically after some time. If we use implicit wait then it will resume execution as soon as element is found but will fail to send keys on element because element is disable. In this scenario we need to wait till element is enable not just till it is found. We can use sleep() here but will increase execution time.
  2. Suppose an alert is open and it takes some time to disappear once user accepts or dismisses it. You need to wait till alert is disappear.
  3. I want to give one real time example. Many applications use toaster messages to show information. There is time defined for a toaster message to disappear. It appears generally at right top corner. Suppose, at right top corner, there is a logout button and when toaster message appears it hides logout button or overlay it. If you try to click on logout button then you will face click intercepted exception. Here, you need to make driver to wait till toaster messages disappear.

There cam be many. Right? Sleep() can be used in above scenarios but will it be optimal? No. Implicit wait will not work in above wait conditions.

Selenium WebDriver provides a special kind of dynamic and customization wait called Explicit wait. Explicit wait is divided in to two parts or we can say that explicit wait can be used in two ways :-

  1. WebDriverWait
  2. FluentWait

Explicit wait can be used to wait till our desired condition or conditions are met or it run out of maximum defined wait time i.e. timeout. It also provides mechanism to decide how frequently you want to check conditions which is called polling time.

Let’s understand working mechanism in short before we see usage.

WebDriverWait and FluentWait both are classes and in a relationship. Wait<T> is a generic functional interface which consists of only method named “until”. This interface is for waiting until a condition is true or not null. “until” method implementation should wait until the condition evaluates to a value that is neither null nor false. Because of this contract, the return type must not be Void. If the condition does not become true within a certain time (as defined by the implementing class), this method will throw a non-specified Throwable which serves the purpose of implementer.

There are two implemented classes of Wait interface:-

  1. A directly implemented generic class named FluentWait<T>
  2. A indirectly implemented class named WebDriverWait

In fact , class WebDriverWait extends FluentWait and FluentWait implements Wait. So WebDriverWait becomes indirect implementation of Wait interface. WebDriverWait is a specialization of FluentWait that used WebDriver instance.

Let’s focus more on WebDriverWait class in this post. In FluentWait things are scattered and WebDriverWait makes it easier by wrapping up things for us to use. In short WebDriverWait reference :-

  1. will ignore NotFoundException by default. NotFoundException is a sub class of WebDriverException and  NoAlertPresentExceptionNoSuchContextExceptionNoSuchCookieExceptionNoSuchElementExceptionNoSuchFrameExceptionNoSuchWindowException are direct sub classes of it.
  2. Default polling interval is 500 ms which comes from FluentWait class.
  3. Constructors in WebDriverWait internally calls FluentWait constructors.

We can override default poling interval time and add more exceptions to be ignored while checking for a condition. We can use WebDriverWait with already defined common wait conditions in ExpectedConditions class or we can write our own by overriding apply() method. All conditions defined in ExpectedConditions class override apply() methods.

Code Snippets

Defining WebDriverWait instance

WebDriverWait class provides three constructors to create its instance. We will see two out of three below :-

// Creating WebDriverWait instance with timeout and default polling interval 
WebDriverWait webDriverWaitWithDefaulPolling = new WebDriverWait(driver, Duration.ofSeconds(30));
// Creating WebDriverWait instance with timeout and custom polling interval
WebDriverWait webDriverWaitWithPollingInterval = new WebDriverWait(driver, Duration.ofSeconds(30), Duration.ofSeconds(2));

Using third constructor you can set a time zone as well default sleeping mechanism between polls. Let’s skip that as of now.

Setting polling interval, timeout duration , message and ignoring more exceptions

// Creating WebDriverWait instance with timeout and default polling interval 
		WebDriverWait webDriverWaitWithDefaulPolling = new WebDriverWait(driver, Duration.ofSeconds(30));
		// To add polling interval
		webDriverWaitWithDefaulPolling.pollingEvery(Duration.ofSeconds(2));
		// To override timeout duration
		webDriverWaitWithDefaulPolling.withTimeout(Duration.ofSeconds(50));
		// To set a message on failure of condition 
		webDriverWaitWithDefaulPolling.withMessage("Condition Failed");
		// Ignoring more exceptions
		webDriverWaitWithDefaulPolling.ignoring(ArithmeticException.class);

Using WebDriverWait instance with ExpectedConditions

webDriverWaitWithDefaulPolling.until(ExpectedConditions.alertIsPresent());

Using WebDriverWait instance with our custom conditions

When we write our own condition then we need to pass WebDriver instance which is always fixed and another parameter is return type of condition. “until” method implementation should wait until the condition evaluates to a value that is neither null nor false.

// Wait till text is equal to Some value or timeout
		webDriverWaitWithDefaulPolling.until(new Function() {
			@Override
			public Boolean apply(WebDriver driver) {
				return driver.findElement(By.linkText("some XPATH")).getText().equals("Some value");
			}
			});

How does WebDriverWait work?

In fact all game is of apply() method of Wait interface. Let me try to explain step by step.

  1. Suppose a WebDriverWait instance is initialized with timeout as 30 seconds, default polling interval as 2 seconds and ignore ArithemeticException. we know by default polling interval will be 500 ms if not overridden and NotFoundException will be ignored by default.
  2. We define a condition in which we want to wait till inner text of element is equal to some value i.e. we are setting a boolean return type of apply() method. If we are using conditions from ExpectedConditions class then it depends on condition we are using.
  3. Driver will check for a condition. If overridden apply() method gives true ( for my scenario) then it will terminate waiting. It it is false then it will wait for provided polling interval duration. Once interval is over then it will recheck for condition. If any exception occurs while checking condition then it will check if that exception is in ignoring list. If it is in ignoring list then driver will ignore it. If not then driver will terminate waiting for condition and throw that exception. This process will be repeated till condition is satisfied or timeout.
  4. If condition is not satisfied till timeout then driver will throw TimeoutException.

So we have covered all basics about WebDriverWait. To learn more in depth with examples then please refer below posts on my blog :-

WebDriverWait & FluentWait In Selenium WebDriver – Let’s Deep Dive

How To Fluent With FluentWait In Selenium WebDriver? – Part 1

How To Fluent With FluentWait In Selenium WebDriver? – Part 2

You can clone the above example from my repo.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

You can find all Selenium related post here.
You can find all API manual and automation related posts here.
You can find frequently asked Java Programs here.

13 thoughts on “Using Explicit Wait As WebDriverWait in Selenium WebDriver

  1. Hi Amod,”

    what actualy this line do “wait.ignoring(ElementNotVisibleException.class)” ?? I’m confused? please elaborate more if possible? And also I had one interview question where they asked how do you handle exception without try catch? Is above wait.ignore statement can be used to handle exception ??

    1. Suppose there is a box full of different types of fruits. You asked one of you friend to pick any fruit from box but ignore and choose again if you get Orange as you don’t like it. While performing any action you might get some exceptions and you want to just ignore some specific exceptions. In that case use ignore.

      1. Thanks Amod. Exception will be ignored till time out? and again after time oue that exception will be shown? Im trying to understand.

        1. Yes till the timeout only it will be ignored. After time out, no restrictions on type of exceptions.

        1. Caller method needs to handle that exception and goes in to hierarchy if not handled. You can refer throws concept in java online.

  2. Thanks for the another great post.

    One of the doubt is if we can use pollingEvery and ignoring in this explicit wait. Then whats the use of fluent wait . I was thinking till today that this pollingEvery and ignoring are the features of fluent wait.

Leave a Reply to Shobhit Cancel reply

Your email address will not be published. Required fields are marked *