我试图在c#中自动化Internet,使用selenium-webdriver来填充外部网站上的公式。有时,代码会随机抛出错误(无法找到名称为== xxx的元素),因为它找不到搜索到的元素。它并不是每次都发生,也不一定发生在同一个地方。
我已经尝试过用下面的代码设置implicitWait,这减少了错误的数量。
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);外部网页在从另一个下拉列表中选择一个选项后(通过重新加载)从下拉列表中更改选择选项。另外,为了拦截这些关键点,我要等待2秒才能找到下拉选项ByName()。
System.Threading.Thread.Sleep(2000);网页需要不到半秒钟的时间来重新加载这个下拉列表,所以2秒就足够了。
你能告诉我我做错了什么,或者为什么why驱动程序似乎不稳定地运行查找元素。我还注意到,只要程序正在运行,就不允许我在计算机上做任何其他事情,否则同样的错误会发生得更频繁。
我的驱动程序-因特网资源管理器8的选项
var options = new InternetExplorerOptions()
{
InitialBrowserUrl = "ExternalPage",
IntroduceInstabilityByIgnoringProtectedModeSettings = true,
IgnoreZoomLevel = true,
EnableNativeEvents = false,
RequireWindowFocus = false
};
IWebDriver driver = new InternetExplorerDriver(options);
driver.Manage().Window.Maximize();--我的最终解决方案在20多个测试中完美地工作,没有一个错误!!
在类中添加了以下内容
enum type
{
Name,
Id,
XPath
};把这个加在我的司机后面
driver.Manage().Window.Maximize();
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));Methode等待元素
private static void waitForElement(type typeVar, String name)
{
if( type.Id)wait.Until(ExpectedConditions.ElementToBeClickable(driver.FindElement(By.Id(name))));
else if(type.Name)wait.Until(ExpectedConditions.ElementToBeClickable(driver.FindElement(By.Name(name))));
else if(type.XPath)wait.Until(ExpectedConditions.ElementToBeClickable(driver.FindElement(By.XPath(name))));
}并在使用元素调用任何事件之前调用methode。
waitForElement(type.Id, "ifOfElement");发布于 2017-09-17 17:58:59
您可以像下面这样使用显式等待:
var wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(10));
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("your locator")));发布于 2017-09-17 15:29:08
Selenium中还有两个选项:
您可以通过Selenium中的WebDriverWait对象使用显式等待。通过这种方式,您可以等待元素出现在页面上。当它们出现时,代码将继续。
举个例子:
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://yourUrl.com");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMinutes(1));
Func<IWebDriver, bool> waitForElement = new Func<IWebDriver, bool>((IWebDriver Web) =>
{Console.WriteLine(Web.FindElement(By.Id("target")).GetAttribute("innerHTML"));
});
wait.Until(waitForElement);此外,还可以使用FluentWait选项。通过这种方式,您可以定义等待条件的最大时间,以及检查条件的频率。
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>()
{
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});https://stackoverflow.com/questions/46265734
复制相似问题