Java Selenium中try-catch块内的NoTouchElementException和isDisplayed()方法

Java Selenium中try-catch块内的NoTouchElementException和isDisplayed()方法,java,selenium,selenium-webdriver,webdriver,Java,Selenium,Selenium Webdriver,Webdriver,我想检查一下阴性情况。 上面的布尔元素未显示,但我必须打印true和false,但它未显示此类元素异常 请帮忙 try{ boolean k= driver.findElement(By.xpath("xpath_of_element")).isDisplayed(); if(!k==true) { System.out.println("true12"); } }catch (NoSuchElementException e) {

我想检查一下阴性情况。 上面的布尔元素未显示,但我必须打印true和false,但它未显示此类元素异常 请帮忙

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);
}

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

  • 元素存在于
  • 元素可见,即显示在
正如您所看到的,它本质上表明元素在中不存在,并且在所有可能的条件下,
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());
        }
List targetElement=driver.findElements(By.xpath(“xpath\u您的\u预期的\u元素”);
试一试{
如果(targetElement>=1){
if(targetElement.isDisplayed()){
System.out.println(“元素存在”);
}
否则{
System.out.println(“元素已找到,但隐藏在页面上”);
}
否则{
System.out.println(“页面上未找到元素”);
}
}捕获(无接触元素例外e){
System.out.println(“查找元素时出现异常:+e.getMessage());
}

因为driver.findElement无法找到任何此类xpath,因此k未被赋值。在打印NoTouchElementException之前,您可以通过删除try catch块来确认这一点……它将再次打印相同的异常。您需要在此处处理xpath,或者由于某些原因,它在页面上不可见。我知道xpath不可见可用,因为单选按钮不可用。但我的测试用例是检查它是否显示print falseAdd your driver.findElement部分(仅在try catch中)。将找不到您的元素,它将引发异常,您可以根据测试用例捕获并打印消息。无需获取布尔值k。在您的情况下,它甚至不会执行在调用if语句时,它在第一行之后直接捕获异常i添加了布尔值和catch exception内的此验证,现在不显示错误,但不显示true或false}catch(NoSuchElementException e){System.out.println(e);}布尔结果=driver.findElement(By.xpath(“”).isDisplayed();if(result==false)System.out.println(“true12”);}else{}System.out.println(“false 12”);}请解释一下你的答案
        if (driver.findElements(xpath_of_element).size() != 0) return true;
        return false;