Selenium:如何通过 xpath 验证元素而不在找不到时抛出异常?

Selenium: How to validate an element by xpath WITHOUT throwing an exception if not found?

我想使用的代码如下:

if(driver.findElement(By.xpath("//xpath_here")
     //call reporting function and say the element was found     
else
{     //call reporting function and say the element was Not found
      //then continue so I can implement my own code if it isn't found
}

它不仅仅是在 catch{} 块中执行上述 Else 中的工作。如有必要,我会添加更多信息。

我试过使用 .isDisplayed() 和 findElements... >= 0 当找不到元素时,这两种方法也会抛出异常。

附带问题:为什么不将这些函数构建为 return 布尔值???

可以使用findElements(),测试长度是否大于0:

if(driver.findElements(By.xpath("//xpath_here")).size() > 0)
     //call reporting function and say the element was found     
else
{     //call reporting function and say the element was Not found
      //then continue so I can implement my own code if it isn't found
}
如果没有元素,

findElements() 不会抛出异常,它会 return 一个长度为 0 的列表。