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
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
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)|