这似乎是在不同版本的驱动程序中反复出现的错误。但是,您可以通过定义定义 Js 代码的方法来解决下拉列表管理问题。
这个例子展示的是C#代码,但是如果你使用其他语言,原理是一样的
public void SelectOption(By by, String value)
{
Actions actions = new Actions(Driver);
IWebElement wele = Driver.FindElement(by);
IJavaScriptExecutor jsExecutor = (IJavaScriptExecutor)Driver;
jsExecutor.ExecuteScript("arguments[0].click();", wele);
jsExecutor.ExecuteScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text.toUpperCase() == arguments[1]){ select.options[i].selected = true; } }", wele, value);
Thread.Sleep(TimeSpan.FromSeconds(1));
}
如果下拉列表中有 onclick="" 或 onchage="" 类型的函数,请记住在 js 代码中定义它们。
如下例所示,定义了 select.onchange()。
public bool SelectOptionOnChange(By by, String value)
{
bool failed = true;
Actions action = new Actions(Driver);
if (!m_sHelper.boolWaitForElementIsDisplayed(by, TimeToWait.med))
m_sHelper.SetErrorMsg("Elemento dropdownlist non identificato: " + value);
else
{
IWebElement dropElement = Driver.FindElement(by);
SelectElement dropOptions = new SelectElement(dropElement);
if (dropOptions.Options.Count == 0)
return true;
try
{
IJavaScriptExecutor jsExecutor = (IJavaScriptExecutor)Driver;
jsExecutor.ExecuteScript("arguments[0].click();", dropElement);
jsExecutor.ExecuteScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text.toUpperCase() == arguments[1]){ select.options[i].selected = true; select.onchange();} }", dropElement, value);
Thread.Sleep(TimeSpan.FromSeconds(1));
failed = false;
} catch (Exception)
{
failed = true;
}
}
return failed;
}