In most of the web applications, Ajax and Javascript are used and when a page is loaded by the browser the elements which we want to interact with may load at different time intervals which makes it difficult to identify the element but also if the element is not located it will throw an ElementNotVisibleException
exception.
This problem can be resolved with waits and Selenium provides two types of waits.
The Implicit Wait tells the Selenium web driver to wait for a certain amount of time when trying to find an element or elements if they are not immediately available before it throws a NoSuchElementException
.
In the following example, we have declared an implicit wait with the time frame of 3 seconds.
webDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
It means that if the element is not located on the web page within that time frame, it will throw an exception.
If you use the implicit wait in selenium it applies to the web driver globally and increases the execution time for the entire script. so it is not always advisable.
The Explicit Wait tells the Selenium web driver to wait for certain conditions or maximum time exceeded before throwing the ElementNotVisibleException
exception.
In the following example, we are instantiating the WebDriverWait
class using the WebDriver
reference, and giving a maximum time frame of 5 seconds.
var wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(10));
wait.Until(f => f.FindElement(By.XPath("//button[.='Search']")));
You should always use an explicit wait since it is dynamic.
Implicit Wait | Explicit Wait |
---|---|
It is applied to all the elements in the script | It is applied only to those elements which are intended by the developer |
We don't need to specify a condition on the element to be located | We need to specify a condition on the element to be located |
It is recommended to use when the elements are located with the time frame specified in implicit wait | It is recommended to use when the elements are taking a long time to load and also for verifying the property of the element like (visibilityOfElementLocated, elementToBeClickable,elementToBeSelected) |