我正在尝试使用 C# 中的 Selenium webdriver 从下拉菜单中选择文本 它可以与 Chrome 浏览器完美配合,但不能与 Firefox 配合使用。谁能帮我解决这个问题。
我使用的代码如下。
public void SelectCountry1(string country)
{
var countryDropDown = Driver.FindElement(By.XPath(xpathidofthecountrydropdown));
countryDropDown .Click();
//Driver.FindElement(By.XPath(xpathidofthecountrydropdown)).Click;
var selectElement = new SelectElement(countryDropDown);
selectElement.SelectByText(country);
}
我能够调用这个函数并且它正在成功执行,没有任何错误消息。我无法选择预期的关键字,即使它存在。
目前我有一个解决方法,即点击同一个 ID 两次,这使得代码可以工作。注释部分未注释但我认为这不是正确的解决方法。让我知道您对此的看法。
谢谢
请您参考如下方法:
是的,它不适用于 Firefox。我不得不使用它作为使用 jQuery 的解决方法。如果页面上没有 jQuery,请随意使用常规 JavaScript 修改此代码。
public static void SetDropdownSelectedOptionByText(IWebDriver driver, string tagId, string newText, int sleepTime)
{
// not working when selecting client id of certain types of ASP.NET user controls
//new SelectElement(driver.FindElement(By.Id(tagId))).SelectByText(newText);
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
js.ExecuteScript("$('#" + tagId + " option:contains(" + Element.NonNullValue(newText) + ")').attr('selected', 'selected')");
js.ExecuteScript("$('#" + tagId + "').change()");
System.Threading.Thread.Sleep(sleepTime); // wait for dependent dropdown to load its values
}
