我想确保在webdriver开始做事情之前,一个元素是存在的。
我正在尝试这样做:
WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));
wait.Until(By.Id("login"));
我主要是挣扎如何设置匿名功能…
我想确保在webdriver开始做事情之前,一个元素是存在的。
我正在尝试这样做:
WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));
wait.Until(By.Id("login"));
我主要是挣扎如何设置匿名功能…
当前回答
你可以在c#中找到类似的东西。
这是我在JUnit - Selenium中使用的
WebDriverWait wait = new WebDriverWait(driver, 100);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));
导入相关的包。
其他回答
使用Mike Kwan提供的解决方案可能会对整体测试性能产生影响,因为隐式等待将在所有FindElement调用中使用。
很多时候,您希望FindElement在一个元素不存在时立即失败(您正在测试一个畸形的页面、缺失的元素等)。使用隐式等待,这些操作将在抛出异常之前等待整个超时到期。默认的隐式等待设置为0秒。
我写了一个小扩展方法到IWebDriver,它添加了一个超时(秒)参数FindElement()方法。这是不言而喻的:
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);
}
}
我没有缓存WebDriverWait对象,因为它的创建非常便宜,这个扩展可以同时用于不同的WebDriver对象,我只在最终需要的时候做优化。
用法很简单:
var driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://localhost/mypage");
var btn = driver.FindElement(By.CssSelector("#login_button"));
btn.Click();
var employeeLabel = driver.FindElement(By.CssSelector("#VCC_VSL"), 10);
Assert.AreEqual("Employee", employeeLabel.Text);
driver.Close();
显式等
public static WebDriverWait wait = new WebDriverWait(driver, 60);
例子:
wait.until(ExpectedConditions.visibilityOfElementLocated(UiprofileCre.UiaddChangeUserLink));
我正在用这个,效果很好:
public static bool elexists(By by, WebDriver driver)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
public static void waitforelement(WebDriver driver, By by)
{
for (int i = 0; i < 30; i++)
{
System.Threading.Thread.Sleep(1000);
if (elexists(by, driver))
{
break;
}
}
}
当然,您可以添加超过30次的尝试,并将周期缩短到1秒以内进行检查。
用法:
waitforelement(driver, By.Id("login"));
IWebElement login = driver.FindElement(By.Id("login"));
login.Click();
因为我使用一个已经找到的IWebElement来分离页面元素定义和页面测试场景,所以可以这样做:
public static void WaitForElementToBecomeVisibleWithinTimeout(IWebDriver driver, IWebElement element, int timeout)
{
new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)).Until(ElementIsVisible(element));
}
private static Func<IWebDriver, bool> ElementIsVisible(IWebElement element)
{
return driver => {
try
{
return element.Displayed;
}
catch(Exception)
{
// If element is null, stale or if it cannot be located
return false;
}
};
}
您不希望在元素更改之前等待太长时间。在这段代码中,webdriver在继续之前最多等待2秒。
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(2000)); wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Name("html-name")));