我想确保在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"));
我主要是挣扎如何设置匿名功能…
当前回答
因为我使用一个已经找到的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;
}
};
}
其他回答
public bool doesWebElementExist(string linkexist)
{
try
{
driver.FindElement(By.XPath(linkexist));
return true;
}
catch (NoSuchElementException e)
{
return false;
}
}
我看到许多解决方案已经张贴,工作很棒!但是,为了防止有人需要其他东西,我想我将发布两个我个人在Selenium c#中使用的解决方案来测试是否存在元素!
public static class IsPresent
{
public static bool isPresent(this IWebDriver driver, By bylocator)
{
bool variable = false;
try
{
IWebElement element = driver.FindElement(bylocator);
variable = element != null;
}
catch (NoSuchElementException){
}
return variable;
}
}
这是第二个:
public static class IsPresent2
{
public static bool isPresent2(this IWebDriver driver, By bylocator)
{
bool variable = true;
try
{
IWebElement element = driver.FindElement(bylocator);
}
catch (NoSuchElementException)
{
variable = false;
}
return variable;
}
}
你可以使用下面的方法
WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0,0,5));
wait.Until(ExpectedConditions.ElementToBeClickable((By.Id("login")));
您不希望在元素更改之前等待太长时间。在这段代码中,webdriver在继续之前最多等待2秒。
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(2000)); wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Name("html-name")));
我混淆了匿名函数和谓词。这里有一个小帮手方法:
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)));
}