我想确保在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"));
我主要是挣扎如何设置匿名功能…
当前回答
// 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)));
}
WebDriverWait将不生效。
var driver = new FirefoxDriver(
new FirefoxOptions().PageLoadStrategy = PageLoadStrategy.Eager
);
driver.Navigate().GoToUrl("xxx");
new WebDriverWait(driver, TimeSpan.FromSeconds(60))
.Until(d => d.FindElement(By.Id("xxx"))); // A tag that close to the end
一旦页面是“交互式的”,这将立即抛出异常。我不知道为什么,但是超时就好像它不存在一样。
也许SeleniumExtras。WaitHelpers很管用,但我没试过。这是官方的,但它被拆分为另一个NuGet包。你可以参考c# Selenium 'ExpectedConditions is obsolete'。
我使用FindElements并检查Count == 0。如果为真,则使用await Task.Delay。这真的不是很有效。
试试下面的代码:
New WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(Function(d) d.FindElement(By.Id("controlName")).Displayed)
使用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;
}
第一个答案是好的,但我的问题是,未处理的异常没有关闭web驱动程序正确,它保持相同的第一个值,我使用的是1秒。
如果遇到同样的问题,重新启动Visual Studio并确保所有异常都得到了正确处理。