Selenium Wait Commands: When we have discussed how to write the first Java selenium automation script, you may have seen the wait statements in those programs. But in this, we are going to discuss those wait statements and different types with real-time examples. In this post, we are going to cover:
- What is Selenium Waits?
- Why Do We Need Waits In Selenium?
- Types of Waits
- Implicit Waits
- Explicit Waits
- Implicit vs Explicit Waits
- Fluent Wait
What is Selenium Wait Commands?
These wait statements are one of the important statements of the automation script because it helps users to fix or know the issue before re-directing to a new web page or as we know that web application can be developed using different technologies like JavaScript and Ajax, so some of the elements are loaded a little bit late so in that case, these wait statements help to wait for some time so that those elements are available in the browser and we can interact with them also.
Why Do We Need Waits In Selenium?
As we the selenium scripts execution is very fast, that means the default wait time duration is 0(Zero), so when we are running our script, then that time may be the application is loaded completely or still it may be in loading only. So if the element is not loaded, then our automation script will throw an “ElementNotVisibleException” exception. But with the help of wait statements, we can able to fix such type of problems.
Now, let’s know what the different types of wait statements present in Selenium WebDriver are. In Selenium, there are three different wait statements or commands are present, and that are:
- Implicit Wait Type
- Explicit Wait Type
- Fluent Wait Type
Implicit Wait
This Implicit Wait idea is mainly borrowed from the Waitr. With the help of Implicit Wait, we are told to the WebDriver wait for the specified amount of time before. If the element is not located within that time interval, then WebDriver will throw an “ElementNotVisibleException”.
Notes: If you have used the implicit wait statements, then the time interval is applied for all the elements and its valid until the browser is open.
The syntax for the implicit wait looks like below:
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
Code Snippet
package com.selenium.practice.waits; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class ImplicitWait { public static void main(String[] args) throws InterruptedException { WebDriver driver; System.setProperty("webdriver.chrome.driver","Path Of Browser Driver"); driver=new ChromeDriver(); driver.manage().window().maximize(); //Implicit Wait - Here the specified Implicit Wait time frame is 15 seconds. //It waits 15 seconds of time frame for the element to load. //It throws an exception, if the element is not loaded within the specified time frame driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS); driver.get("https://softwaretestingo.blogspot.com/"); driver.close(); } }
Note 1: Implicit, Explicit, and Fluent waits are dynamic waits. What are dynamic waits? Consider a situation where you have given a TimeOut value of 20 seconds. If the element is loaded in 5 seconds, then rest 15 seconds will be ignored. It won’t wait until the TimeOut value is completed, i.e. 20 seconds. That’s why all waits are considered as dynamic waits.
Note 2: Implicitly wait is applied globally, which means it is always available for all the web elements throughout the driver instance. It implies that if the driver is interacting with 100 elements, then implicitly wait is applicable for all the 100 elements.
This is easy to apply, but it also introduces a few drawbacks as well. Because the time interval is applicable for all the elements, the execution time also increased. So to avoid such types of issues Selenium WebDriver introduces another new type of wait that’s called Explicit wait.
Explicit Wait
This is a concept of dynamic waits that waits for some particular conditions. That means we can use such type of waits to pause the execution of our script until a specific time or a condition is meet. Unlike implicit wait, this Explicit wait is applicable for the particular element or instance. If after waiting for that specified time also it is not able to locate the elements, then it will throw an “ElementNotVisibleException”.
To understand why we have explicit wait in selenium WebDriver and when we should use in the selenium programs, we will try to know with a couple of examples.
Conditions For Explicit Wait in Selenium WebDriver
Suppose there is a login page and after successful, the user is redirected to the dashboard page. So when it redirects the login page to the dashboard page sometimes, it takes 10 seconds, and sometimes it takes 20 seconds. So in this situation, we can take the help of explicit wait to wait until the specified page is not present.
Syntax:
WebDriverWait wait=new WebDriverWait(WebDriveReference,TimeOut);
In the above syntax, as you can see that we have created an instance or object of WebDriver wait and in that we have pass two parameters that are driver reference and timeout.
Example Program:
package com.selenium.practice.waits; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; 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 ExplicitWait { public static void main(String[] args) throws InterruptedException { WebDriver driver; System.setProperty("webdriver.chrome.driver","Path Of Browser Driver"); driver=new ChromeDriver(); WebDriverWait wait=new WebDriverWait(driver, 20000); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS); driver.get("https://softwaretestingo.blogspot.com/2020/08/how-to-use-explicit-wait-in-selenium.html"); driver.findElement(By.xpath("//button[contains(text(),'Click me to start timer')]")).click(); WebElement element=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//p[text()='Automation Testing']"))); Boolean status=element.isDisplayed(); if(status) { System.out.println("Element Is Visible"); } else { System.out.println("Element Not Visible"); } driver.close(); } }
At the time of using the explicit wait we can use the below expected condition:
- alertIsPresent()
- elementSelectionStateToBe()
- elementToBeClickable()
- elementToBeSelected()
- frameToBeAvaliableAndSwitchToIt()
- invisibilityOfTheElementLocated()
- invisibilityOfElementWithText()
- presenceOfAllElementsLocatedBy()
- presenceOfElementLocated()
- textToBePresentInElement()
- textToBePresentInElementLocated()
- textToBePresentInElementValue()
- titleIs()
- titleContains()
- visibilityOf()
- visibilityOfAllElements()
- visibilityOfAllElementsLocatedBy()
- visibilityOfElementLocated()
Implicit vs Explicit Waits
Implicit Wait | Explicit Wait |
Applies to all elements in a test script. | Applies only to specific elements as intended by the user. |
In Implicit wait, we define a code to wait for a certain amount of time when trying to find an element or elements. | In Explicit wait, we write a code to define the wait statement for a specific condition to be satisfied until the wait reaches its timeout period. |
No need to specify “ExpectedConditions” on the element to be located | Must always specify “ExpectedConditions” on the element to be located |
Most effective when used in a test case in which the elements are located with the time frame specified in implicit wait | Most effective when used when the elements are taking a long time to load. Also useful for verifying property of the element such as visibilityOfElementLocated, elementToBeClickable,elementToBeSelected |
driver.manage().timeouts(). implicitWait(10,TimeUnit.SECONDS); | WebElement element = wait.until (ExpectedConditions.elementToBeClickable(By.id(“someId”))); |
Fluent Wait
The fluent wait is used to instruct the WebDriver to wait for a condition and also check the condition frequently with the specified time interval. And after the specified time interval if the locator is not able to locate the element, then it will throw “ElementNotVisibleException”.
As we have discussed in explicit wait that, if we have specified 20 seconds to wait for it will wait until the specified time interval is completed. So if the element is available in 5 seconds, then we have wait still 15 more seconds to execute the next statements. To overcome such a situation we can use the fluent wait there because fluent wait tries to find out the element in the different interval (In each interval) of time until it finds the element or the time is over.
Syntax:
Wait wait = new FluentWait(WebDriver reference) .withTimeout(timeout, SECONDS) .pollingEvery(timeout, SECONDS) .ignoring(Exception.class);
Let us take an implementation of Fluent wait
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(30, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class);
In the above statements you can see that, we have mentioned withTimeout is 30 seconds that means we are going to maximum 30 seconds at the same time we have mentioned polling every 5 seconds which means every 5 seconds to verify that the specified condition is a success or failure. In finally we have direct to WebdDiver to ignore NoSuchElementException if it occurs during the interval.
Selenium Fluent Wait Commands Example Program
package com.selenium.practice.waits; import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; import java.util.function.Function; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.FluentWait; public class FluentWaitExample { public static void main(String[] args) { WebDriver driver; System.setProperty("webdriver.chrome.driver","Path Of Browser Driver"); driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://softwaretestingo.blogspot.com/2020/08/fluent-wait-page-for-practice.html"); driver.findElement(By.xpath("//button[contains(text(),'Click Me - Fluent Wait')]")).click(); FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(30, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class); @SuppressWarnings("unused") WebElement element = wait.until(new Function<WebDriver, WebElement>() { @Override public WebElement apply(WebDriver driver) { WebElement element = driver.findElement(By.xpath("//p[@id='demo']")); String getTextOnPage = element.getText(); if(getTextOnPage.equals("Softwaretestingo - DEMO PAGE")) { System.out.println(getTextOnPage); return element; } else { System.out.println("FluentWait Failed"); return null; } } }); driver.close(); } }
During writing automation script for your project, these three types of wait (implicit, explicit and fluent wait) statements help us to solve the
Description
Synchronization errors. I hope with this selenium WebDriver tutorial post I can clear your doubts and gives you a better understanding of this topic. If still, you have any doubts, then you can comment in the comment section.
What is pageLoadTimeout
Selenium defines different timeouts and different wait mechanisms. One of the timeouts is focused on the time a webpage needs to be loaded. the pageLoadTimeout limits the time that the script allows for a web page to be displayed. If the page loads within the time, then the script continues. If the page does not load within the timeout, the script will be stopped by a TimeoutException.
How to set the timeout
The timeout is set at the driver level. After creating the driver instance with the appropriate capabilities.
What is affected by the Timeout
This timeout setting will remain in force for the remainder of the script (until changed) and will affect any calls that generate a new web-page. This includes the get() method in Java o. However, the timeout may be delayed until the first findElement() call for the new page, since the navigation method may return asynchronously.
As a result, when using the timeout, webpage navigation should be executed under the control of try-catch clauses that catch the TimeoutException. For example:
//Define the timeout RemoteWebDriver driver = new RemoteWebDriver(new URL("https://" + host + "/nexperience/perfectomobile/wd/hub"), capabilities); driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS); // Use the timeout when navigating to a webpage try { driver.get(myWebPage); driver.findElementByXpath(verificationField); } catch (TimeoutException e) { System.out.println("Page: " + myWebPage + " did not load within 40 seconds!"); // treat the timeout as needed }
Leave a Reply