nosuchelementexception:在检查条件时,使用给定的搜索参数无法在页面上找到元素



我正在写一个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:使用给定的搜索参数无法在页面上找到元素。"触发和测试用例失败。

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

你的代码会发生两件事。

  1. 您正在尝试定位网页上的元素
  2. 一旦你有了元素,你就可以验证它是否可见。

所以如果所有的元素都在页面上找到,那么只有它会工作,否则你总是会得到NoSuchElementException

这是预期的行为。

如果元素没有找到,那么Selenium将抛出

org.openqa.selenium.NoSuchElementException:

因此,如果元素本身没有在HTML DOM中找到,那么.isDisplayed()实际上没有任何意义。

,因为.isDisplayed()表示查找元素是否为

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

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

解决方案:

现在讨论解决方案,我建议您将此代码包装在try和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块中的大小。

最新更新