Selenium:如何通过xpath验证元素如果没有找到则抛出异常?

时间:2015-01-30 21:56:06

标签: selenium xpath

我想使用的代码如下:

if(driver.findElement(By.xpath("//xpath_here")
     //call reporting function and say the element was found     
else
{     //call reporting function and say the element was Not found
      //then continue so I can implement my own code if it isn't found
}

除了在catch {}块中执行上述Else中的工作之外,还有更多内容。如有必要,我会添加更多信息。

我尝试过使用.isDisplayed()和findElements ...> = 0这些都会在找不到元素时抛出异常。

附带问题:为什么不构建这些函数来返回布尔值???

1 个答案:

答案 0 :(得分:4)

您可以使用findElements(),并测试长度是否大于0:

if(driver.findElements(By.xpath("//xpath_here")).size() > 0)
     //call reporting function and say the element was found     
else
{     //call reporting function and say the element was Not found
      //then continue so I can implement my own code if it isn't found
}
如果没有元素,

findElements()将不会抛出异常,它将返回长度为0的列表。