【问题标题】:NoSuchElementException with isDisplayed() method within try catch block in Selenium在 Selenium 的 try catch 块中使用 isDisplayed() 方法的 NoSuchElementException
【发布时间】:2018-12-02 19:28:27
【问题描述】:

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

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

【问题讨论】:

  • 因为 driver.findElement 无法找到任何这样的 xpath,因此在打印 NoSuchElementException 之前没有为 k 分配任何值。您可以通过删除 try catch 块来确认这一点......它将再次打印相同的异常。您需要在此处处理 xpath,或者由于某些原因它在页面上不可见。
  • 我知道 xpath 不可用,因为单选按钮不可用。但我的测试用例是检查它是否显示 print false
  • 在 try catch only 中添加您的 driver.findElement 部分。找不到您的元素,它会抛出异常,您可以根据您的测试用例捕获并打印消息。无需在 Boolean k 中获取值。在您的情况下,它甚至不执行 if 语句,它直接在第一行之后捕获异常
  • 我在 catch 异常中添加了布尔值和此验证,现在错误未显示但未显示真假 } catch (NoSuchElementException e) { System.out.println(e); } 布尔结果 = driver.findElement(By.xpath("")).isDisplayed(); if (result==false) System.out.println("true12"); } 其他 { } System.out.println("false12"); }

标签: java selenium selenium-webdriver webdriver


【解决方案1】:
        if (driver.findElements(xpath_of_element).size() != 0) return true;
        return false;

【讨论】:

  • add对你的回答做一些解释
【解决方案2】:

在检查元素的显示状态之前,您应该使用下面的代码来验证给定的 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());
        }

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-05-27
      • 1970-01-01
      • 2021-03-29
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-31
      相关资源
      最近更新 更多