使用Selenium WebDriver测试元素是否存在? [英] Test if element is present using Selenium WebDriver?

查看:129
本文介绍了使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆