我正在尝试做一个简单的任务,尝试使用显示的文本在下拉列表中选择一个值。情况如下。
我的HTML看起来像。
<div id="TestContainer" class="col-md-4">
<select onchange="Test()">
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
<option>Test4</option>
</select>
</div>
通过使用硒,我想使用下拉菜单中的第二项,即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;
}
在以上两种情况下,代码均不会中断,不会引发异常,但是不会选择该值,并且似乎什么也没有发生。
我正在使用的硒的版本如下。
<package id="Selenium.Support" version="2.53.1" targetFramework="net452" />
<package id="Selenium.WebDriver" version="2.53.1" targetFramework="net452" />
<package id="WebDriver.GeckoDriver"version="0.9.0"targetFramework="net452" />
我也正在使用最新版本的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");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句