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