使用Selenium webdriver处理Select2

Jus*_*tin 22 c# selenium jquery-select2 selenium-webdriver

我一直在试图从使用selenium webdriver的ajax启用的select2选择列表中选择一个选项.我已经设法使用IE webdriver而不是firefox.这是我对IE的hacky解决方案

 public static void SetSelect2Option(this IWebDriver driver, By locator, string subContainerClass, string searchTerm, TimeSpan? ajaxWaitTimeSpan = null)
    {
        var select2Product = driver.FindElement(locator);
        select2Product.Click();
        var searchBox = driver.FindElement(By.CssSelector(subContainerClass + " .select2-input"));
        searchBox.SendKeys(searchTerm);
        if (ajaxWaitTimeSpan != null)
        {
            driver.Manage().Timeouts().ImplicitlyWait(ajaxWaitTimeSpan.Value);
        }
        var selectedItem = driver.FindElements(By.CssSelector(subContainerClass + " .select2-results li")).First();
        selectedItem.Click();
        selectedItem.SendKeys(Keys.Enter);
    }
Run Code Online (Sandbox Code Playgroud)

在Firefox中,此解决方案一直运行到SendKeys调用的位置,它只是挂起并继续下一步而不实际触发select2的事件来填充所选项目.

我也厌倦了使用http://code.google.com/p/selenium/wiki/AdvancedUserInteractions api,结果相似.

有没有人遇到过类似的问题?

Yi *_*eng 28

你能告诉我们定位器吗?这是我测试没有任何问题.

注意

  1. 要打开选择框,请使用css选择器#s2id_e1 .select2-choice或等效的XPath.
  2. #select2-drop通过css选择器#select2-drop:not([style*='display: none'])或等效的XPath 确保是可见的.
  3. 确保使用subContainerClass+ .select2-results li.select2-result-selectable或等效的XPath 单击可选项.
var driver = new FirefoxDriver();
driver.Url = "http://ivaynberg.github.io/select2/";

var select2Product = driver.FindElement(By.CssSelector("#s2id_e1 .select2-choice"));
select2Product.Click();

string subContainerClass = "#select2-drop:not([style*='display: none'])";
var searchBox = driver.FindElement(By.CssSelector(subContainerClass + " .select2-input"));
searchBox.SendKeys("Ohio");

var selectedItem = driver.FindElements(By.CssSelector(subContainerClass + " .select2-results li.select2-result-selectable")).First();
selectedItem.Click();
Run Code Online (Sandbox Code Playgroud)

  • FWIW,我不得不使用'ClickAt'5,5而不是点击来实现这一点. (2认同)

Ale*_*ndr 6

我花了一些时间让它在FF,Chrome和IE8-11中运行.

  1. 单击下拉箭头
  2. 单击所需的li

这是我的简化代码:

[FindsBy(How = How.ClassName, Using = "select2-arrow")]
private IWebElement Selector { get; set; }

private void selectItem(string itemText)
{
    Selector.Click();  // open the drop
    var drop = Driver.FindElement(By.Id("select2-drop"));    // exists when open only
    var item = drop.FindElement(By.XPath(String.Format("//li[contains(translate(., '{0}', '{1}'), '{1}')]", itemText.ToUpper(), itemText.ToLower())));
    item.Click();
}
Run Code Online (Sandbox Code Playgroud)