我想确保在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"));
我主要是挣扎如何设置匿名功能…
当前回答
显式等
public static WebDriverWait wait = new WebDriverWait(driver, 60);
例子:
wait.until(ExpectedConditions.visibilityOfElementLocated(UiprofileCre.UiaddChangeUserLink));
其他回答
这是一个可重用的函数,用于使用显式等待等待DOM中出现的元素。
public void WaitForElement(IWebElement element, int timeout = 2)
{
WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromMinutes(timeout));
wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException));
wait.Until<bool>(driver =>
{
try
{
return element.Displayed;
}
catch (Exception)
{
return false;
}
});
}
第一个答案是好的,但我的问题是,未处理的异常没有关闭web驱动程序正确,它保持相同的第一个值,我使用的是1秒。
如果遇到同样的问题,重新启动Visual Studio并确保所有异常都得到了正确处理。
// Wait up to 5 seconds with no minimum for a UI element to be found
WebDriverWait wait = new WebDriverWait(_pagedriver, TimeSpan.FromSeconds(5));
IWebElement title = wait.Until<IWebElement>((d) =>
{
return d.FindElement(By.ClassName("MainContentHeader"));
});
我混淆了匿名函数和谓词。这里有一个小帮手方法:
WebDriverWait wait;
private void waitForById(string id)
{
if (wait == null)
wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));
//wait.Until(driver);
wait.Until(d => d.FindElement(By.Id(id)));
}
我正在用这个,效果很好:
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();