Implict Wait and Explicit Wait in Selenium | Handle synchronization using wait

Implict Wait and Explicit Wait in Selenium

Implicit Wait and Explicit Wait in Selenium WebDriver

Implicit and Explicit Wait in Selenium

In our previous tutorials, we have been using either sleep or selenium wait command, which is not at all recommended. We were using these should-not-be-used commands for simplicity. 

After going through the implicit and explicit wait tutorial, update all previous code and replace wait/sleep with the implicit or explicit wait as an exercise.

Synchronization problem

It happens sometimes that you execute a test script and it got failed, you re-execute it without any modification and it just passes. Clicking on Google auto-suggest search results is the classic example where you’d have experienced it.

WebDriver execution is so fast that our test does not wait for the desired element to appear and try to interact with it, which eventually lead to test failure due to unable to locate element. To overcome such situations where some wait is required, we use implicit or explicit wait.

Implicit wait in Selenium

The implicit wait is used to wait for a specific time until an element appears. 

  • If the element fails to appear within the given time, unable to locate element or element not found exception is thrown.
  • If the element appears before the specified time, the system will not wait further and perform the operation on the element.

The implicit wait is associated with WebDriver object and hence is applied globally. The syntax for the implicit wait is:

driver.manage().timeouts().implicitlyWait(10L, TimeUnit.SECONDS);

implicit wait accepts two arguments, the first argument is a long value and the second argument is TimeUnit. The long value could be a numeric value like 10, 20 etc. and TimeUnit could be millisecond, second etc.

Above code is defined globally for driver object, where the system will wait for 10 seconds before throwing any error.

Lab Exercise:

Open makemytrip.com, enter “united” in From dropdown and click on second auto-populated value.

Solution:

First, we will try the selenium code in the traditional way, without using any wait statement.

Implicit and Explicit Wait in Selenium

Following is the selenium script trying to search for united and clicking on second element.

package pkg;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class TestClass {

    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/home/dhawal/Downloads/chromedriver/chromedriver");
        WebDriver driver = new ChromeDriver();
              
        driver.get("https://www.makemytrip.com/");
        
        driver.findElement(By.xpath("//input[@id='hp-widget__sfrom']")).sendKeys("united");
        driver.findElement(By.xpath("//span[contains(text(),'Dubai, United Arab Emirates')]")).click();
        driver.close();

    }

}

If you run above code, it will fail due to element not found exception. Script execution happened so fast that our script tried to click on the second element before it even appears on the screen. Another issue which you would have observed is that united text is appended to the default text which is already displayed in From drop down.

This dropdown is not a select dropdown which we have discussed in previous tutorials. This is an ajax search which filters results dynamically as user type in each character.

Introduce the implicitlyWait() method (changes from the above code is highlighted in bold color) and force the web page to wait until 10 seconds before performing any operation, and if element appears before 10 seconds, the script will work upon the locator and execution resumes.

package pkg;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class TestClass {

    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/home/dhawal/Downloads/chromedriver/chromedriver");
        WebDriver driver = new ChromeDriver();
        
        //implicityWait() is associated with driver. Now whenever this driver is used, implicit wait is called automatically.
        driver.manage().timeouts().implicitlyWait(10L, TimeUnit.SECONDS);
        
        
        driver.get("https://www.makemytrip.com/");
        
        //clear the default value in From field
        driver.findElement(By.xpath("//input[@id='hp-widget__sfrom']")).clear();
        
        //send desired text after clearing default value
        driver.findElement(By.xpath("//input[@id='hp-widget__sfrom']")).sendKeys("united");
        
        //xpath for second element
        driver.findElement(By.xpath("//span[contains(text(),'Dubai, United Arab Emirates')]")).click();
        driver.close();

    }

}

Explicit wait in Selenium

We learned that implicit wait is tied to the driver object, and once defined it will stick to driver object (implicit wait is global in nature) and evaluate the timeout for each element as mentioned in implicitlyWait() statement.

Suppose there is an element which gets enabled after the time greater than as defined in implicitylyWait() statement. In this case, our script will always fail. The explicit wait is associated with the element state (if the element is enabled, disabled, clickable etc.) and our script will explicitly wait until the condition is true.

The syntax for an explicit wait is:

WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
wait.until(ExpectedConditions.presenceOfElementLocated(By locator);

WebDriverWait is the class which is used for the explicit wait. We start writing the explicit wait by first creating its object wait and then use this object to apply any wait condition. If you type above code in eclipse IDE, you’ll get numerous option if you put a ‘.’ after ExpectedConditions. We are using presenceOfElementLocated(By) method to verify if the element By is present or not, and the system will wait only for timeOutInSeconds

Let’s modify our implicit wait code and try to fit explicit wait in it.

package pkg;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class TestClass {

    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/home/dhawal/Downloads/chromedriver/chromedriver");
        WebDriver driver = new ChromeDriver();
        
        // Create object of WebDriverWait class
        WebDriverWait wait = new WebDriverWait(driver, 5L);
        
        
        driver.get("https://www.makemytrip.com/");
        
        //clear the default value in From field
        driver.findElement(By.xpath("//input[@id='hp-widget__sfrom']")).clear();
        
        //send desired text after clearing default value
        driver.findElement(By.xpath("//input[@id='hp-widget__sfrom']")).sendKeys("united");
        
        //wait until the element defined under By.xpath is present. Default wait time is 5 seconds as specified in WebDriverWait 
        wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//span[contains(text(),'Dubai, United Arab Emirates')]"))).click();
        
        driver.close();

    }

}




In a nutshell, if you just want to wait arbitrarily without impacting the wait time, use implicit wait. And if you want to wait till an element state is changed, use explicit wait.

Author: Dhawal Joshi

A post-graduate in MCA, ISTQB & ITIL certified QA with more than 8 years of experience in QA working with a CMMI Level 5 organization as System Analyst. I started my automation journey with HP UFT(formerly known as QTP) and for the past few years, I am using Selenium for automation. I also have experience in Android Application Development, Java, HTML, and VBScript. When I am not working, I like to spend time with my family, cooking and learning new developments in IT.

43 thoughts on “Implict Wait and Explicit Wait in Selenium | Handle synchronization using wait

  1. Hi, I do think this is a great website. I stumbledupon it ;
    ) I may return yet again since I saved as a favorite it.
    Money and freedom is the best way to change, may you be rich
    and continue to guide other people. I couldn’t resist commenting.
    Perfectly written! I needed to thank you for this great read!!
    I absolutely enjoyed every little bit of it.
    I have got you book-marked to check out new stuff you http://dell.com

  2. Asking questions are truly good thing if you are not understanding
    anything fully, except this post presents pleasant understanding yet.

  3. I must thank you for the efforts you’ve put in writing
    this blog. I’m hoping to see the same high-grade content from you later
    on as well. In fact, your creative writing abilities has encouraged me to get my very own blog now 😉

  4. Hey there just wanted to give you a quick heads up. The text in your post seem to be running off the screen in Opera.
    I’m not sure if this is a format issue or
    something to do with internet browser compatibility but I thought I’d post to let you know.
    The layout look great though! Hope you get the issue solved soon. Kudos

  5. Hey There. I found your blog the usage of
    msn. That is a very smartly written article. I will be sure to bookmark
    it and return to learn extra of your helpful information. Thank you for the post.
    I will certainly return.

  6. Its like you read my mind! You appear to know a lot about this,
    like you wrote the book in it or something.
    I think that you can do with a few pics to drive the message home
    a little bit, but instead of that, this is great blog.

    A great read. I will definitely be back.

  7. I think this is one of the most significant information for me.
    And i’m glad reading your article. But should remark on some general things, The website style is ideal, the articles is really
    nice : D. Good job, cheers

  8. That is really fascinating, You’re an overly professional blogger.

    I have joined your feed and stay up for searching for more of your wonderful post.
    Also, I have shared your site in my social networks

  9. Hi there would you mind letting me know which hosting company you’re using?

    I’ve loaded your blog in 3 completely different browsers and
    I must say this blog loads a lot faster then most.
    Can you suggest a good web hosting provider at a honest price?
    Kudos, I appreciate it!

  10. My relatives always say that I am killing my time here at web, however I know I
    am getting knowledge everyday by reading thes fastidious articles.

  11. I needed to thank you for this fantastic read!! I definitely enjoyed
    every little bit of it. I have got you saved as a favorite to check out new things you post…

  12. Hey there, You’ve done an incredible job. I’ll certainly digg it and personally
    suggest to my friends. I am sure they will be benefited from this
    site.

  13. That is a very good tip particularly to those fresh to the blogosphere.

    Short but very precise info… Thank you for sharing this one.
    A must read post!

  14. I do accept as true with all of the concepts you have introduced on your post.

    They are very convincing and can certainly work. Still, the posts are
    too quick for beginners. May just you please prolong them a
    little from next time? Thanks for the post.

  15. Just want to say your article is as amazing. The clearness in your post
    is simply great and that i could suppose you’re knowledgeable on this subject.
    Fine together with your permission allow me to take hold
    of your RSS feed to stay up to date with forthcoming post.
    Thanks a million and please carry on the rewarding work.

  16. Greetings from Ohio! I’m bored to death at work so I decided to check out
    your website on my iphone during lunch break. I enjoy the information you present here and can’t wait
    to take a look when I get home. I’m surprised at how quick your blog loaded
    on my phone .. I’m not even using WIFI, just 3G ..

    Anyways, great blog!

  17. Hey there I am so delighted I found your blog, I really found you by accident, while I
    was looking on Aol for something else, Regardless I
    am here now and would just like to say cheers for a incredible post and a all round thrilling blog (I also love the theme/design), I don’t have time to go through it all at the
    minute but I have book-marked it and also added
    your RSS feeds, so when I have time I will be back to
    read more, Please do keep up the superb work.

  18. Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or
    something. I think that you can do with a few pics to drive the message home a little bit, but other than that, this
    is magnificent blog. A great read. I will definitely be back.

  19. That is a really good tip particularly to those new to the blogosphere.
    Brief but very accurate information… Thank you
    for sharing this one. A must read post!

  20. Your style is unique compared to other folks I have read stuff from.
    Thanks for posting when you have the opportunity, Guess I’ll just book mark this site.

  21. great points altogether, you just won a emblem new reader.
    What might you recommend about your publish that you simply
    made a few days ago? Any sure?

  22. Please let me know if you’re looking for a article author for your weblog.

    You have some really great posts and I feel I would be a
    good asset. If you ever want to take some of the load
    off, I’d really like to write some articles for your blog in exchange for a link back to mine.

    Please blast me an email if interested. Thank you!

Leave a Reply

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