【发布时间】: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