我想在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");