Reputation: 386
I am working with automation now and again have faced a problem. In general, I have logic in my code where I need to check for the existence of an element and next step will depend on the result of checking. But base instruments of Selenium return only boolean true otherwise NoSuchElementException. But I need "false".
As on my previous project, I use simple wrapper for solving this problem now:
private boolean isDisplayedOnPage(WebElementFacade wef){
try{
return wef.isDisplayed();
} catch (NoSuchElementException nsee){
return false;
}
}
It works perfectly but the use of the exception confuses me. Also, I read about "wait" but it doesn't return false as well, only lets me ignore the exception. Are there built-in instruments for solving this problem in Selenium? Or maybe someone can offer a more elegant way to solve it?
Upvotes: 1
Views: 6401
Reputation: 21
An unclean workaround could be to check the DOM for a unique String that symbolizes your WebElement and then write into a boolean if it could be found.
This loop will check the DOM for the string around every second for 60 times with refreshing the page if nothing was found:
for (int i= 0; i <60; i++){
String pageSource = browser.getPageSource().toString();
boolean elementThere = pageSource.contains("uniqueStringOfElement");
if (elementThere){
browser.WebElement.click()
break;
}
else {
Thread.sleep(1000);
browser.navigate().refresh();
}
}
Upvotes: 0
Reputation: 131
Boolean bool = my_driver.findElements(By.id("my element id")).size()>0;
this will help you.
Upvotes: 4
Reputation: 27486
One of the core tenets of the raw WebDriver API is the expectation that the user knows the state of the DOM for the page being automated. This means that, in the logic of the API, calling findElement
using a locator of an element that doesn’t exist is an exceptional condition, making the throwing of an exception perfectly legitimate. While one could argue that the expectation built into the API behavior is faulty, that’s beyond the scope of this answer. If you need Boolean logic for whether an element exists, you need a wrapper method, as you’ve already discovered. Within that wrapper method, you have two choices:
Use findElement
and catch the NoSuchElementException
. Note that using WebDriverWait
implicitly catches this exception for you, so is a semantic equivalent.
Use findElements
(note the "s"), which returns an empty list without throwing an exception if the element doesn’t exist.
Upvotes: 4