2017-09-17 62 views
0

我想在c#中使用selenium-webdriver自动化Internet Explorer以在外部网站上填充表单。 有时代码会抛出随机错误(无法找到名称== xxx的元素),因为它无法找到搜索到的元素。这不是每次都发生,不一定在相同的地方。ImplicitWait似乎无法在Selenium Webdriver中等待元素

我已经尝试用下面的代码来设置implicitWait,它减少了错误的数量。

driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); 

外部网页在从另一个下拉菜单中选择一个选项后,从下拉菜单中更改选择选项(通过重新加载)。 为了额外拦截这些关键点,我等待2秒钟,然后尝试查找下拉选项ByName()

System.Threading.Thread.Sleep(2000); 

该网页用了不到半秒的时间来重新加载这个下拉菜单,所以2秒就足够了。

你能告诉我我做错了什么或为什么webdriver似乎运行如此不稳定地找到元素。 我也注意到,只要程序正在运行,我不允许在计算机上执行其他任何操作,否则会出现相同的错误。为Internet Explorer

我的司机选项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))));     
    } 

,并调用梅索德事件与元素

waitForElement(type.Id, "ifOfElement"); 

回答

1

您可以使用显式的等待这样的例子:

var wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(10)); 
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("your locator"))); 
1

你有硒两个选项:

您可以使用显式等待通过硒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")); 
     } 
}); 
相关问题