首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Selenium WebDriver测试元素是否存在?

使用Selenium WebDriver测试元素是否存在?
EN

Stack Overflow用户
提问于 2011-11-03 15:36:19
回答 15查看 394.2K关注 0票数 179

有没有一种方法可以测试元素是否存在?任何findElement方法都会以异常结束,但这不是我想要的,因为元素可能不存在,这没有关系,这不是测试失败,所以异常不是解决方案。

我找到了这篇文章:Selenium c# Webdriver: Wait Until Element is Present,但这篇文章是为C#写的,我不太擅长。有人能把代码翻译成Java吗?很抱歉,伙计们,我在Eclipse中尝试过,但是我不能正确地在Java代码中使用它。

代码如下:

代码语言:javascript
复制
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);
    }
}
EN

回答 15

Stack Overflow用户

发布于 2012-10-24 17:56:40

如果一个私有方法简单地查找元素并确定它是否存在,情况会是这样的:

代码语言:javascript
复制
private boolean existsElement(String id) {
    try {
        driver.findElement(By.id(id));
    } catch (NoSuchElementException e) {
        return false;
    }
    return true;
}

这将是非常简单的,并且可以完成工作。

编辑:您甚至可以更进一步,接受一个By elementLocator作为参数,如果您想通过id以外的其他东西来查找元素,则消除了问题。

票数 59
EN

Stack Overflow用户

发布于 2013-01-05 02:24:24

我发现这适用于Java:

代码语言:javascript
复制
WebDriverWait waiter = new WebDriverWait(driver, 5000);
waiter.until( ExpectedConditions.presenceOfElementLocated(by) );
driver.FindElement(by);
票数 15
EN

Stack Overflow用户

发布于 2011-11-09 06:17:25

代码语言:javascript
复制
public static WebElement FindElement(WebDriver driver, By by, int timeoutInSeconds)
{
    WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
    wait.until( ExpectedConditions.presenceOfElementLocated(by) ); //throws a timeout exception if element not present after waiting <timeoutInSeconds> seconds
    return driver.findElement(by);
}
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7991522

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档