使用Selenium WebDriver测试元素是否存在? [英] Test if element is present using Selenium WebDriver?
问题描述
有没有一种方法可以测试元素是否存在?任何findElement方法都将以异常结尾,但这不是我想要的,因为它可能是一个元素不存在并且没关系,这不是测试失败,因此异常不能成为解决方案.
Is there a way how to test if an element is present? Any findElement method would end in an exception, but that is not what I want, because it can be that an element is not present and that is okay, that is not a fail of the test, so an exception can not be the solution.
我发现了这篇文章: Selenium c#Webdriver:等到元素出现 但这是针对C#的,我不是很擅长.任何人都可以将代码翻译成Java吗?抱歉,我在Eclipse中进行了尝试,但我没有将其正确地插入Java代码中.
I've found this post: Selenium c# Webdriver: Wait Until Element is Present But this is for C# and I am not very good at it. Can anyone translate the code into Java? I am sorry guys, I tried it out in Eclipse but I don't get it right into Java code.
这是代码:
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
将返回一个空列表.
要检查是否存在某个元素,您可以尝试
To check that an element is present, you could try this
Boolean isPresent = driver.findElements(By.yourLocator).size() > 0
如果找到至少一个元素,则返回true;否则,返回false.
This will return true if at least one element is found and false if it does not exist.