Test if element is present using Selenium WebDriver?

Use findElements instead of findElement.

findElements will return an empty list if no matching elements are found instead of an exception.

To check that an element is present, you could try this

Boolean isPresent = driver.findElements(By.yourLocator).size() > 0

This will return true if at least one element is found and false if it does not exist.

The official documentation recommends this method:

findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead.


What about a private method that simply looks for the element and determines if it is present like this:

private boolean existsElement(String id) {
    try {
        driver.findElement(By.id(id));
    } catch (NoSuchElementException e) {
        return false;
    }
    return true;
}

This would be quite easy and does the job.

Edit: you could even go further and take a By elementLocator as parameter, eliminating problems if you want to find the element by something other than id.


I found that this works for Java:

WebDriverWait waiter = new WebDriverWait(driver, 5000);
waiter.until( ExpectedConditions.presenceOfElementLocated(by) );
driver.FindElement(by);