gpt4 book ai didi

c# - 如何编写等待 selenium webElement 的通用方法

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:51 24 4
gpt4 key购买 nike

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

最佳答案

我会使用扩展方法:

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

关于c# - 如何编写等待 selenium webElement 的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36631000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com