2

我正在尝试使用 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,这会使代码正常工作。注释部分未注释但我认为这不是正确的解决方法。让我知道你对此的看法。

谢谢

4

2 回答 2

0

通常,选择类无需您单击下拉菜单即可处理选择。它应该在 FF 和 Chrome 中都可以工作,即 Select 有一些其他问题。尽量不要点击下拉按钮。如果 Select 类没有按照它假设的方式运行,则尝试单击和导航选项发送向上向下键,然后按 Enter。

于 2012-08-03T22:23:52.817 回答
0

是的,它不适用于 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
}
于 2012-08-07T06:56:14.407 回答