2017-09-17 74 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")); 
     } 
}); 
相關問題