NoSuchElementException with isDisplay() 方法在 Try catch block



我想检查负面条件。 上面布尔元素没有显示,但我必须打印真假,但它没有显示这样的元素异常 请帮忙。

try{
boolean k= driver.findElement(By.xpath("xpath_of_element")).isDisplayed();
if(!k==true)
{
System.out.println("true12"); 
}
}catch (NoSuchElementException e) {
System.out.println(e);
}

元素有两个不同的阶段,如下所示:

  • HTML DOM 中存在的元素
  • 元素可见,即显示在DOM 树中

正如您所看到的NoSuchElementException,它本质上表明该元素不存在于视口中,并且在所有可能的情况下isDisplayed()该方法将返回false。因此,要验证这两个条件,您可以使用以下解决方案:

try{
if(driver.findElement(By.xpath("xpath_of_the_desired_element")).isDisplayed())
System.out.println("Element is present and displayed");
else
System.out.println("Element is present but not displayed"); 
}catch (NoSuchElementException e) {
System.out.println("Element is not present, hence not displayed as well");
}

在检查元素的显示状态之前,您应该使用以下代码来验证给定 xpath 是否存在至少一个或多个元素。

List<WebElement> targetElement =  driver.findElements(By.xpath("xpath_your_expected_element"));
try {
if(targetElement>=1) {
if(targetElement.isDisplayed()) {
System.out.println("Element is present");
}
else {
System.out.println("Element is found, but hidden on the page");
}
else {
System.out.println("Element not found on the page");
}
}catch (NoSuchElementException e) {
System.out.println("Exception in finding the element:" + e.getMessage());
}
if (driver.findElements(xpath_of_element).size() != 0) return true;
return false;

最新更新