使用 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.
官方文档推荐这种方法:
findElement 不应用于查找不存在的元素,而应使用 findElements(By) 并断言零长度响应.
findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead.
这篇关于使用 Selenium WebDriver 测试元素是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!