如何编写等待selenium webElement的泛型方法

时间:2016-04-14 18:21:07

标签: c# selenium

因此,每次我想搜索此WebDriverWait webDriverWait元素并将其与until...一起使用时,我想编写泛型方法,而不是写入:

static IWebElement FindElement(ExpectedConditions expectedConditions, By by, int timeOut)
{
    WebDriverWait webDriverWait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeOut));
    IWebElement element =
    webDriverWait.Until(ExpectedConditions.ElementExists(By.Id("foo")));
}

我想传递这个方法的几个参数:

1. ExpectedConditions. 
2. By option.
3. time out in seconds.

因为您可以看到这几乎已经准备就绪,但我如何在我的方法中添加ExpectedConditionsselector类型?

1 个答案:

答案 0 :(得分:1)

我会使用扩展方法:

public static IWebElement WaitElementPresent(this IWebDriver driver, By by, int timeout = 10) {
    return new WebDriverWait(driver, TimeSpan.FromSeconds(timeout))
        .Until(ExpectedConditions.ElementExists(by));
}

public static IWebElement WaitElementVisible(this IWebDriver driver, By by, int timeout = 10) {
    return new WebDriverWait(driver, TimeSpan.FromSeconds(timeout))
        .Until(ExpectedConditions.ElementIsVisible(by));
}

public static IWebElement Wait(this IWebDriver driver, Func<IWebDriver, IWebElement> condition, int timeout = 10) {
    return new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)).Until(condition);
}

以下是一些使用示例:

// wait for an element to be present and click it
driver.Wait(ExpectedConditions.ElementExists(By.Id("..."))).Click();

// wait for an element to be visible and click it
driver.Wait(ExpectedConditions.ElementIsVisible(By.Id("...")), 5).Click();

// wait for an element to be present and click it
driver.WaitElementPresent(By.Id("...")).Click();

// wait for an element to be visible and click it
driver.WaitElementVisible(By.Id("...")).Click();

请注意,扩展方法必须放在静态类中:

https://msdn.microsoft.com/en-gb/library/bb383977.aspx