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

本文关键字:泛型方法 selenium-webElement 等待 何编写 | 更新日期: 2024-09-08 05:11:32

所以我不想每次都写搜索元素这个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类型放在我的方法中呢?

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

我会使用一个扩展方法:

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