Wednesday, October 15, 2014

Ways to implement WebDiver Wait

In previous post I had discussed about locating element whose x-path is dynamic, so in continuation to the same in this discussion  I will share a very common problem i.e errors of exception for no such element.

So what's the issue and how we should cater this ?

Problem:-
The ajax in page to get new data or info and it takes a few seconds more after page load to load that element which you are looking for.

Solution:-
To handle this in Selenium Webdriver we have 3 ways as per below:-
1. Thread.sleep().
2. implicit Wait().
3. Explicit wait.

Explanation:-
1. Thread.sleep(milliseconds)

It will stop the execution of thread to sleep as per the number defined in milliseconds as parameter for instance:-
Thread.sleep(10000);
It will throw Interrupted Exceptions for which  you need to add try catch or add exceptions for the same. It will pause your script for the time that you mentioned as parameter.

Not recommended to use this as it increases execution time and its  preferred to use when element is loaded but its not visible or enabled.

2. Implicit Wait()

It will tell  WebDriver to wait for that particular element if not available at that moment. So,  WebDriver will not throw the exception of no such element immediately.

Syntax:-
driver.manage().timeouts().implicitlywait(90,TimeUnit.SECONDS);

Here we have passed 2 arguments i.e "90" and "TimeUnit.SECONDS" of java.util.concurrent.TimeUnit.SECONDS so, it will wait for 90 secs and will not throw Exception of no such element till that time.

3. Explicit wait or Webdriver wait()
It will check in every 500 millisec until it throws successful or timeout.

Syntax:-
WebDriverWait wait = new WebDriverWait(driver, 90);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("some path")));

Expected conditions with explicit wait can be of following which is not there in implicit wait is as per below :-

elementToBeClickable
elementToBeSelected

and many more options are avalible just hit crtl+space after period sign.

No comments:

Post a Comment