isElementPresent is very slow in case if element does not exist.

0
0

I am using below code to check for element on my web page

private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
catch (Exception e)
{
return false;
}
}

I need to check in my program if a particular region appears in result as below

isElementPresent(By.xpath(".//*[@id='header']")));

If this is present this function completes quickly but if above is not present then it run for very long.

Could some one please help me in resolving this issue so that this check can be performed quickly?

  • You must to post comments
0
0

Here you are missing somethings that is why it is waiting If there is not element. findElement will wait for an element implicitly specified time. so need to set that time to zero in that method.

isElementPresent(WebDriver driver, By by) {  
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
} finally {
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
}

There are 4 important things going on here. In order:

  1. Setting implicity_wait to 0 so that WebDriver does not implicitly wait.

  2. Returning True when the element is found.

  3. Catching the NoSuchElementException and returning False when we discover that the element is not present instead of stopping the test with an exception.

  4. Setting implicitly_wait back to 30 after the action is complete so that WebDriver will implicitly wait in future.

  • You must to post comments
Showing 1 result
Your Answer
Post as a guest by filling out the fields below or if you already have an account.
Name*
E-mail*
Website