简体   繁体   中英

What can be used if I want to check if the element is present or not in selenium webdriver?

I just want to check if the element is present on the page or not?

I am confused with what can be used. What is feasible to use isDisplayed() or isPresent() ?

What is the difference between these two?

  1. There is no isPresent function
  2. The isDisplayed returns True only if the element is displayed on the webpage and is actually visible.
  3. If you just want to check if the element is present then you can do one of the following:

    • Put the code for findElement inside a try/catch block. If it goes inside catch with NoSuchElementException then the element is not present.
    • Do findElements instead of findElement and if length of the list returned by findElements is zero, then the element is not present.
    • In both the cases you need to make sure that you are finding the desired element using a unique selector.

to simplify.. I've posted code below

public static boolean isElementPresent(final WebDriver driver, By by) {
        try {
            waitForElement(driver, by, 2);
            driver.findElement(by);

            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

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