Selenium:Firefox驱动程序,使用c#中的SelectElement从下拉列表中选择项目无法正常工作

我正在尝试通过使用显示的文本来尝试选择下拉列表中的值。 场景如下。

我的HTML看起来像。

Test1 Test2 Test3 Test4

通过使用selenium我想使用下拉列表中的第二个项目test2。 我为此编写的C#代码是。

 FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(); service.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"; string localURL = "http://localhost:82/"; using (IWebDriver driver = new FirefoxDriver(service)) { driver.Navigate().GoToUrl(localURL); var div = driver.FindElement(By.Id("TestContainer")); div.Click(); IWebElement dropDownListBox = div.FindElement(By.TagName("select")); SelectElement demoSelect = new SelectElement(dropDownListBox); demoSelect.SelectByText("Test2"); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(2)); } 

除了以上所述,我甚至尝试逐个迭代选项并选择下面的相应项目也无济于事。

 if (option.Text.Equals("Test2")) { option.Click(); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(2)); break; } 

在上述两种情况下,代码都不会中断并且不会抛出任何exception,但是不会选择该值,似乎没有发生任何事情。

我正在使用的selenium版本如下。

    

另外我使用的是最新版本的firefox(48.0)

以前有人遇到过这个问题吗? 如果你能指出我正确的方向,那将是很棒的。

如果你已经尝试了SelectElement所有方法来选择一个option但是没有成功,那么下面是尝试使用IJavascriptExecutor另一个解决方案: –

  IWebElement dropDownListBox = driver.FindElement(By.cssSelector("#TestContainer select")); ((IJavaScriptExecutor)driver).ExecuteScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", dropDownListBox, "Test2"); 

完整代码:

 using (IWebDriver driver = new FirefoxDriver(service)) { driver.Navigate().GoToUrl(localURL); IWebElement dropDownListBox = driver.FindElement(By.cssSelector("#TestContainer select")); ((IJavaScriptExecutor)driver).ExecuteScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", dropDownListBox, "Test2"); } 

我也遇到了这个问题。

    

并运行FireFox版本48.0 ..

将FireFox更新到版本49.0.1后,SelectElement类终于能够完成其工作。

Javascriptexecutor可以通过网站检测到,我遇到了同样的问题,我解决了它创建了一个webelement下拉列表。 这是代码:

 WebElement dropdown = driver.findElement(By.id("serverLogin")); dropdown.sendKeys(server); dropdown.sendKeys(Keys.ENTER); 

这样就没有必要升级firefox了