简体   繁体   中英

Existence of an element using Selenium

I have seen a couple of ways to test if an element exists. One way:

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

And another way:

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

but adding an exception to test something isn't good practice and using the size method will take too long if you have an implicit wait.

Are there any other efficient ways to test for existence? If not, which of the two will be the preferred way to do it?

From the findElement(By) documentation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM