【问题标题】:Selenium isDisplayed() is returning NoSuchElementException when I expect false当我期望 false 时,Selenium isDisplayed() 返回 NoSuchElementException
【发布时间】:2021-05-05 16:59:04
【问题描述】:

当我的代码运行并且元素存在时,eleExists 设置为 true,但是当它不存在而不是设置为 false 时,我得到 NoSuchElementException。 我想知道这是否是 Selenium 中的错误?

try{

    boolean eleExists = driver.findElement(By.cssSelector("Element cssSelector")).isDisplayed();
    if(eleExists)
    {
             // do stuff
    }
    else{
            // do other stuff
    }

}catch (Exception e) {
    System.out.println(e);
}

我看到了这个问题: Selenium Webdriver - 在 If 语句中使用 isDisplayed() 不起作用

解决方案是将代码包装在 try catch 中,我已经这样做了,现在它正在工作。 但我很想知道这种行为是否有意。

【问题讨论】:

  • 这是预期行为。该元素不存在。
  • 您正在检查“isDisplayed”...这与“exists”不同。该元素可能存在,但不可见/显示。当元素不存在时抛出 NoSuchElement。值得注意的是 findElements() 不会抛出那个错误,而是返回一个空数组。

标签: selenium


【解决方案1】:

Web 元素可以有多种状态。发生这种情况是因为一个元素可以在或不在页面上,不可见或启用。 处理这个问题的一个好习惯是通过 selenium waits.

一些显着的网络元素状态是:

存在: - 元素在 DOM 上,但我们不能说它是启用还是可见。

可见: - 元素在 DOM 上并且可见,但我们不能说它是否启用(例如,如果它是一个按钮,则不可能点击它)。

可点击或启用: - 元素完全可操作

这是一个使用等待与元素交互的代码示例。

...
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
...
selector = (By.TAG_NAME, 'body')

# this returns the element as driver.find_element()
element = WebDriverWait(driver, timeout).until(EC.element_to_be_clickable(selector))

element.click()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2016-02-08
    • 1970-01-01
    • 2020-10-18
    相关资源
    最近更新 更多