Friday, August 23, 2019

selenium - wait


  • 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:
Explicit waits are confined to a particular web element. Explicit Wait is code you define to wait for a certain condition to occur before proceeding further in the code. If the element is not found during the wait, excepation will be thrown. The polling frequency is 500ms. Explicit Wait is only applied to the specific elemnt.

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
a class in selenium api. Using Fluent Wait, you can set wait for a specific element, set the polling frequency, max wait time and set to ignore specific exceptions.








No comments:

Post a Comment

API interview questions

  https://www.katalon.com/resources-center/blog/web-api-testing-interview-questions/ Top 50+ Web API Testing Interview Questions [Ultimate l...