有没有办法测试一个元素是否存在?任何 findElement 方法都会以异常结束,但这不是我想要的,因为它可能是一个元素不存在并且没关系,这不是测试失败,所以异常不能成为解决方案。
我找到了这篇文章:Selenium c# Webdriver: Wait Until Element is Present 但这是针对 C# 的,我不太擅长。任何人都可以将代码翻译成Java吗?抱歉各位,我在 Eclipse 中尝试过,但在 Java 代码中没有正确使用。
这是代码:
public static class WebDriverExtensions{
public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds){
if (timeoutInSeconds > 0){
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
return wait.Until(drv => drv.FindElement(by));
}
return driver.FindElement(by);
}
}
最佳答案
使用 findElements
代替 findElement
。
findElements
将返回一个空列表,而不是异常。
要检查一个元素是否存在,你可以试试这个
Boolean isPresent = driver.findElements(By.yourLocator).size() > 0
如果至少找到一个元素,则返回 true,如果不存在,则返回 false。
The official documentation推荐这种方法:
findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead.
关于java - 使用 Selenium WebDriver 测试元素是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7991522/