- why?
The elements in a web page load time can vary.
Using "wait", we can enable the script to wait some time before throwing "NO Such Element" exception
C#
- Thread.Sleep()
Thread.Sleep(3000);
Thread.Sleep(new TimeSpan(0,0,3));
Thread.Sleep(TimeSpan.FromSeconds(3));
Not a good practice. The waiting time is been hard coded and no matter what, the program will wait the time span.
- Implicit Waits:
Implicit waits tell to the WebDriver to poll the DOM ( frequency is 250ms) for certain amount of time before it throws an exception, if the element is not found immediatelly. That means if the element is found immediatelly, it won't wait. If the elemement is not found immediately, it will re run the find element every 250ms till it find the element and quit. Or if the element is not found during the time, it will throw an exception after the timeout.
Once we set the implicit wait, it will apply to the whole live web driver instance. That means for every finding element operation, there will be an implicit wait.
But as we know, different element has different loading time. For some elements, if it is not been found immediately, we want it stop and quit. We don't want to wait the extra time. And for some other elements, we want it to wait longer time, not the set time in implicit wait.
Implicit wait is flexible than Thread Sleep. But still not a good choice.
driver.Manage().Timeouts().ImplicitWait = new TimeSpan(0,0,5);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
- Explicit Wait:
c# install Dotnetseleniumextras.waithelper
WebDriverWait wait = new WebDriverWait(driver,TimeSpan.FromSeconds(10));
IWebElement element = wait.Until(driver => driver.FindElement(By.Name("q")));
Also we can use try catch to catch the exception.
- Fluent Wait
No comments:
Post a Comment