【问题标题】:org.openqa.selenium.NoSuchElementException: An element could not be located on the page using the given search parameters while check in if conditionorg.openqa.selenium.NoSuchElementException:在检查条件时,使用给定的搜索参数无法在页面上找到一个元素
【发布时间】:2021-09-01 19:42:03
【问题描述】:

我正在编写一个 if 条件来查找项目中的元素位置。

    if (!(driver.findElement(MobileBy.xpath(ObjRepoProp.getProperty("searchTextBox_XPATH"))).isDisplayed()
            || driver.findElement(MobileBy.xpath(ObjRepoProp.getProperty("routeOverview_XPATH"))).isDisplayed()
            || driver.findElement(MobileBy.xpath(ObjRepoProp.getProperty("scrollNavigationDrawer_XPATH")))
                    .isDisplayed())) {
        throw new IllegalStateException("This is not Destination Input page");
    }

在此代码中,如果其中一个条件为真,则“org.openqa.selenium.NoSuchElementException:使用给定的搜索参数无法在页面上找到一个元素。”触发器和测试用例失败。

【问题讨论】:

    标签: java selenium if-statement


    【解决方案1】:

    让我们首先了解它是如何工作的。

    您的代码发生了两件事。

    1. 您正在尝试定位网页上的元素
    2. 拥有元素后,您将验证它是否可见。

    因此,如果所有元素都在页面上找到并找到,那么只有它会起作用,否则您将始终得到NoSuchElementException。

    【讨论】:

      【解决方案2】:

      这是预期的行为。

      看看如果元素没有找到那么 Selenium 会抛出

      org.openqa.selenium.NoSuchElementException:

      所以如果元素本身没有在 HTML DOM 中找到,.isDisplayed() 并没有真正的意义。

      因为.isDisplayed()是用来查找元素是否是

      """Whether the element is visible to a user."""
      

      因此,当元素(您使用的任何定位器)不可用时,Selenium 将在调用 .isDisplayed() 之前抛出 org.openqa.selenium.NoSuchElementException:

      解决办法:

      现在谈论解决方案,我建议您将此代码包装在 try and catch 正文中。

      代码:

      try {
          if (!(driver.findElement(MobileBy.xpath(ObjRepoProp.getProperty("searchTextBox_XPATH"))).isDisplayed()
                  || driver.findElement(MobileBy.xpath(ObjRepoProp.getProperty("routeOverview_XPATH"))).isDisplayed()
                  || driver.findElement(MobileBy.xpath(ObjRepoProp.getProperty("scrollNavigationDrawer_XPATH")))
                  .isDisplayed())) {
              throw new IllegalStateException("This is not Destination Input page");
          }
      }
      catch (NoSuchElementException ne) {
          System.out.println("In catch block to handle no such element");
          ne.printStackTrace();
      }
      catch(Exception e) {
          System.out.println("In catch block to handle Generic exception");
          Exception e.printStackTrace();
      }
      

      如果您仍然看到问题,您可以尝试使用findElements 并在 if 块中检查它的大小。

      【讨论】:

        猜你喜欢
        • 2019-08-18
        • 2019-08-30
        • 1970-01-01
        • 1970-01-01
        • 2014-09-30
        • 2016-12-26
        • 1970-01-01
        • 2017-01-15
        • 2019-06-23
        相关资源
        最近更新 更多