Selenium Webdriver:处理NoSuchElementException的最佳实践

经过大量的搜索和阅读,我仍然不清楚使用Webdriver处理失败的断言的最佳方法。 我原以为这是一个常见的核心function。 我想做的就是:

  • 寻找一个元素
  • 如果有的话 – 告诉我
  • 如果没有 – 告诉我

我想为非技术受众呈现结果,因此让它使用完整堆栈跟踪抛出’NoSuchElementExceptions’是没有用的。 我只想要一个好消息。

我的测试:

@Test public void isMyElementPresent(){ // WebElement myElement driver.findElement(By.cssSelector("#myElement")); if(driver.findElement(By.cssSelector("#myElement"))!=null){ System.out.println("My element was found on the page"); }else{ System.out.println("My Element was not found on the page"); } } 

当我强制失败时,我仍然会抛出NoSuchElementException。 我还需要试一试吗? 我是否可以在不需要System.out.println的情况下合并Junit断言和/或Hamcrest来生成更有意义的消息?

我遇到过类似的情况。 根据findElementfindElements API的Javadoc ,似乎findElement行为是设计的。 您应该使用findElements检查不存在的元素。

因为在您的情况下,WebElement可能不存在,您应该使用findElements

我用这个如下。

 List elems = driver.findElements(By.cssSelector("#myElement")); if (elems.size == 0) { System.out.println("My element was not found on the page"); } else System.out.println("My element was found on the page"); } 

你可以做些什么来检查元素是否存在

  public boolean isElementExists(By by) { boolean isExists = true; try { driver.findElement(by); } catch (NoSuchElementException e) { isExists = false; } return isExists; } 

如何在try-catch中使用xPath,传递元素类型,属性和文本如下?

 try { driver.FindElement( By.XPath(string.Format("//{0}[contains(@{1}, '{2}')]", strElemType, strAttribute, strText))); return true; } catch (Exception) { return false; }