Selenium Webdriver C#-未选择Firefox下拉菜单文本

本文关键字:Firefox 下拉菜单 文本 选择 Webdriver C#- Selenium | 更新日期: 2024-09-19 13:01:45

我正在尝试使用C中的Selenium网络驱动程序从下拉菜单中选择一个文本#它与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);
}

我能够调用这个函数,并且它正在成功执行,没有任何错误消息。我无法选择预期的关键字event,尽管它存在。

目前,我有一个变通方法,在同一个id上单击两次,这样代码就可以工作了。注释部分未注释,但我认为这不是正确的解决方法。让我知道你对此的看法。

感谢

Selenium Webdriver C#-未选择Firefox下拉菜单文本

是的,它不能很好地与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
}

通常select类处理选择,甚至不需要单击下拉菜单。它应该在FF和Chrome中都能工作,即Select有一些其他问题。尽量不要单击下拉按钮。如果Select类的工作方式与它所设想的不一样,请尝试单击和导航选项,发送上下键,然后按enter键。