c# - 这是等待 selenium WebElement 的最佳方式吗?

标签 c# selenium

public static IWebElement FindElement(ExpectedConditions expectedConditions, By by, int timeoutInSeconds)
{
    DefaultWait<IWebDriver> wait = new DefaultWait<IWebDriver>(driver);
    wait.Timeout = TimeSpan.FromSeconds(timeoutInSeconds);
    wait.PollingInterval = TimeSpan.FromMilliseconds(10000);
    wait.IgnoreExceptionTypes(typeof(NoSuchElementException));

    IWebElement element =
        wait.Until<IWebElement>(ExpectedConditions.ElementIsVisible(by));
}

我的问题:

如何放置此 expectedConditions 而不是我方法中当前的内容?

我尝试改变:

    IWebElement element =
        wait.Until<IWebElement>(ExpectedConditions.ElementIsVisible(by));

用这个:

    IWebElement element =
        wait.Until<IWebElement>(expectedConditions(by));

并收到此错误:

Method name expected.

最佳答案

Until 方法需要一个谓词作为第一个参数。 谓词是一个定期调用的函数,直到它返回不同于 nullfalse 的内容。

所以在你的情况下你需要让它返回一个谓词而不是一个IWebElement:

public static Func<IWebDriver, IWebElement> MyCondition(By locator) {
    return (driver) => {
        try {
            var ele = driver.FindElement(locator);
            return ele.Displayed ? ele : null;
        } catch (StaleElementReferenceException){
            return null;
        }
    };
}

// usage
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement element1 = wait.Until(MyCondition(By.Id("...")));

等于:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement element = wait.Until(ExpectedConditions.ElementIsVisible(By.Id("...")));
element.Click();

你也可以使用 lambda 表达式

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement element = wait.Until((driver) => {
    try {
        var ele = driver.FindElement(By.Id("..."));
        return ele.Displayed ? ele : null;
    } catch (StaleElementReferenceException){
        return null;
    }
});
element.Click();

或者扩展方法:

public static IWebElement WaitElementVisible(this IWebDriver driver, By by, int timeout = 10) {
    return new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)).Until((drv) => {
        try {
            var ele = drv.FindElement(by);
            return ele.Displayed ? ele : null;
        } catch (StaleElementReferenceException){ 
            return null;
        } catch (NotFoundException){ 
            return null; 
        }
    });
}


// usage
IWebElement element = driver.WaitElementVisible(By.Id("..."));
element.Click();

如您所见,有很多方法可以等待元素处于特定状态。

关于c# - 这是等待 selenium WebElement 的最佳方式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36661913/

相关文章:

javascript - Nightwatch 执行()不是预期后的方法

python selenium 点击第n个元素

javascript - Selenium IDE - 选择OkOnNextConfirmation 而不使用assertConfirmation?

C# - 使用 LINQ 将带重复项的分隔字符串数组转换为字典

c# - ServiceStack Razor View 未编译

c# - 从物理路径获取相对虚拟路径

地铁的 C# 数据结构

ruby-on-rails-3 - 如何在 iframe 中填充文本字段中的值

java - 如何在java和selenium中从excel读取浮点值

C# TagLib 为 Mp3 设置专辑封面