Selenium WebDriver - 测试元素是否存在 [英] Selenium WebDriver - Test if element is present
问题描述
有没有办法测试元素是否存在?任何findElement方法都会以异常结束,但这不是我想要的,因为它可能是一个元素不存在而且没关系,这不是测试的失败,因此异常不能成为解决方案。
我发现这篇文章: Selenium c#Webdriver:等到元素存在
但这是针对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));
返回wait.Until(drv => drv.FindElement(by));
}
返回driver.FindElement(by);
}
}
使用 findElements
而不是 findElement
。
<$ c $如果找不到匹配的元素而不是异常,则c> findElements 将返回一个空列表。
要检查元素是否存在,可以尝试这个
布尔值isPresent = driver.findElements(By.yourLocator).size()> 0
如果找到至少一个元素,则返回true,如果不存在则返回false。 / p>
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.
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.
This is the 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);
}
}
Use findElements
instead of findElement
.
findElements
will return an empty list if no matching elements are found instead of an exception.
To check that an element is present, you could try this
Boolean isPresent = driver.findElements(By.yourLocator).size() > 0
This will return true if at least one element is found and false if it does not exist.
这篇关于Selenium WebDriver - 测试元素是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!