【问题标题】:Assert Absence of element in the web page, giving NoSuchElementException断言网页中没有元素,给出 NoSuchElementException
【发布时间】:2018-09-22 11:59:06
【问题描述】:

需要断言网页中没有这样的元素, 当尝试使用fieldValueBox.isDisplayed(); 而不是“false”时,它会抛出“NoSuchElementFound”异常。 现在我正在使用'try catch'并在'catch'中做出决定

【问题讨论】:

    标签: java selenium selenium-webdriver webdriver nosuchelementexception


    【解决方案1】:

    isDisplayed() 方法返回一个基于现有元素的布尔值。意思是,如果你想检查一个存在的元素是否显示在网页上(例如,不隐藏或任何东西),这个方法将正常工作。

    在您的情况下, fieldValueBox 可能不存在。因此,isDisplayed() 方法将尝试返回一个不存在对象的布尔值。

    try catch 在这里可以帮助您,所以这是一种正确的方法。还有其他几种方法,请检查:

    WebDriver: check if an element exists?

    How do I verify that an element does not exist in Selenium 2

    【讨论】:

      【解决方案2】:

      如果该元素不在页面上,那么您将收到“NoSuchElementFound”异常。您可以尝试使用定位器检查元素的数量是否为零:

      private boolean elementNotOnPage(){
          boolean elementIsNotOnPage = false;
      
          List<WebElement> element = driver.findElements(yourLocator);
      
          if(element.size() == 0){
              elementIsNotOnPage = true;
          }
      
          return elementIsNotOnPage;
      
      }
      

      【讨论】:

      • findElements(locator) 将等待元素(无论您在测试中定义了多少时间),无论元素是否存在。有时,try catch 会以更简单的方式完成这项工作。
      【解决方案3】:

      当你试图断言你的网页中没有这样的元素:

      fieldValueBox.isDisplayed();
      

      现在,如果您查看 isDisplayed() 方法的 Java 文档,它与 Interface WebElement 相关联。因此,在调用 isDisplayed() 方法之前,您必须先定位/搜索元素,然后才能调用 isDisplayed()isEnabled()isSelected() 或任何其他相关方法。

      粗略地说,在您之前的步骤中,当您尝试通过 findElement(By by)findElements(By by) 方法查找/定位所需的 WebElement 时,引发了 NoSuchElementFound 异常。当findElement(By by)findElements(By by) 方法引发NoSuchElementFound 异常时,fieldValueBox.isDisplayed(); 的以下行将不会被执行。

      解决方案

      您的问题的一个可能解决方案是在 try-catch {} 块内调用 findElement(By by),如下所示:

      try {
          WebElement fieldValueBox = driver.findElement(By.id("element_id"));
          bool displayed = fieldValueBox.isDisplayed();
          //use the bool value of displayed variable
      } catch (NoSuchElementException e) {
          //perform other tasks
      }
      

      【讨论】:

        猜你喜欢
        • 2019-03-16
        • 1970-01-01
        • 2013-05-02
        • 1970-01-01
        • 2020-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多