Implicit and Explicit Waits in Selenium
Why are waits required in Selenium?
In UI automation, waits are required because certain elements get loaded on the page asynchronously, so after triggering an event a page may get loaded successfully but some of its elements may still not get loaded.
This causes elementNotFound exception while locating the element. In such cases, we are left with using Thread.sleep() i.e. a static wait that will halt the test execution for some specified time and then perform the next step.
As Thread.sleep() will wait for the specified time no matter if the elements get visible before that time. So, using Thread.sleep() is never advisable in UI automation.
To avoid this Selenium provides different types of waits, out of which Implicit and Explicit waits are most commonly used.
An implicit wait when used is set to the WebDriver instance and is applied to all the web elements. In implicit wait the webdriver polls the DOM to check the availability of the webElement and waits till the maximum time specified before throwing NoSuchElementException.
WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
In the above code snippet, the value 20 specified in the implicit wait method is the maximum time in seconds till which WebDriver will wait before throwing NoSuchElementException while locating a WebElement.
Unlike implicit waits, the explicit waits are applied to each and every web element. In explicit wait, certain conditions are defined for which the WebDriver instance waits before locating web elements or performing actions on them. Some of the most common conditions specified in explicit waits are-
elementToBeClickable, presenceOfElementLocated etc.
WebDriverWait wait = new WebDriverWait(driver, 15); wait.until(ExpectedConditions.presenceOfElementLocated(ElementLocator));
Here the WebDriver instance will wait until the condition specified is met i.e. the presence Of Element located by the ElementLocator with the maximum wait time of 15 seconds after which if the condition is still not met then it will throw an exception.
Do check our complete step by step Selenium tutorial for complete beginners-