如果我想检查元素是否存在于 selenium webdriver 中,可以使用什么?

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

我只想检查该元素是否出现在页面上?

我对可以使用什么感到困惑。 isDisplayed()isPresent()哪个可行?

这两个有什么区别?

  1. 没有isPresent功能
  2. isDisplayedreturnsTrue仅当该元素显示在网页上并且实际可见时。
  3. 如果您只想检查元素是否存在,那么您可以执行以下操作之一:

    • findElement 的代码放在 try/catch 块中。如果它进入 catchNoSuchElementException 则该元素不存在。
    • 执行 findElements 而不是 findElement,如果 findElements 返回的列表长度为零,则该元素不存在。
    • 在这两种情况下,您都需要确保使用唯一的选择器找到所需的元素。

为了简化..我在下面发布了代码

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

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