我想确保在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"));
我主要是挣扎如何设置匿名功能…
当前回答
你也可以使用隐式等待:
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
隐式等待是告诉WebDriver轮询DOM 在试图找到一个或多个元素时的时间 暂时不可用。默认设置为0。设置好后, 为WebDriver对象实例的生命周期设置隐式等待。
其他回答
我们可以这样实现:
public static IWebElement WaitForObject(IWebDriver DriverObj, By by, int TimeOut = 30)
{
try
{
WebDriverWait Wait1 = new WebDriverWait(DriverObj, TimeSpan.FromSeconds(TimeOut));
var WaitS = Wait1.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.PresenceOfAllElementsLocatedBy(by));
return WaitS[0];
}
catch (NoSuchElementException)
{
Reports.TestStep("Wait for Element(s) with xPath was failed in current context page.");
throw;
}
}
这是一个可重用的函数,用于使用显式等待等待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;
}
});
}
使用c#扩展方法:我们可以解决等待直到元素可见的问题。 一个特定元素的最大reties是100。
public static bool WaitForElementToBeVisible(IWebDriver browser, By by)
{
int attemptToFindElement = 0;
bool elementFound = false;
IWebElement elementIdentifier = null;
do
{
attemptToFindElement++;
try
{
elementIdentifier = browser.FindWebElement(by);
elementFound = (elementIdentifier.Displayed && elementIdentifier.Enabled) ? true : false;
}
catch (Exception)
{
elementFound = false;
}
}
while (elementFound == false && attemptToFindElement < 100);
return elementFound;
}
你可以在c#中找到类似的东西。
这是我在JUnit - Selenium中使用的
WebDriverWait wait = new WebDriverWait(driver, 100);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));
导入相关的包。
你也可以使用隐式等待:
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
隐式等待是告诉WebDriver轮询DOM 在试图找到一个或多个元素时的时间 暂时不可用。默认设置为0。设置好后, 为WebDriver对象实例的生命周期设置隐式等待。