Selenium2的Select对象在IE8中没有触发onchange事件

时间:2011-12-01 18:57:44

标签: java internet-explorer-8 webdriver selenium-webdriver

在我的应用中,我有两个<select>标签。第一个更改第二个中的选项并在onchange事件中启用它。

当我使用Selenium2提供的Select对象时,它在IE8中运行时不会触发该事件(在FF和我手动操作时效果很好)。

Select select = new Select(getElementByName(name));
element.selectByValue(value);

第一次<select>按预期更改。但是,第二个<select>仍为空并禁用。我尝试了这个解决方法:

if(ie) {
    WebElement select = getElementByName(name);
    WebElement option = select.findElement(By.cssSelector("[value='"+value+"']"));

    List<WebElement> options = select.findElements(By.cssSelector("option"));
    //select the first element
    options.get(0).click();

    //make sure the select is focused
    select.click(); //open
    select.click(); //close

    Keyboard keyboard = getWebDriver().getKeyboard();
    for(int i = 0; i < options.size() && option.getAttribute("selected") == null; i++) {
         keyboard.pressKey(Keys.DOWN);
         //note: if i do a Thread.sleep(100); here, it works more consistently, but still not 100%
    }
} else {
     // Do the above snippet
}

但现在我的结果不一致了。始终会选择所需的<option>,而有时只会触发事件。

显然,最好的选择是让Select在IE8中运行。还有其他人看过这个问题吗?看起来像Selenium2中的一个错误。有没有已知的解决方法呢?

3 个答案:

答案 0 :(得分:1)

在#selenium IRC聊天室与一些Selenium人交谈后,我决定解决这个问题:

WebElement selectElement = getElementByName(name);
Select select = new Select(selectElement);
element.selectByValue(value);
if(usingIE) {
    webDriver.executeScript("$(arguments[0]).fireEvent('change');", selectElement);
}

答案 1 :(得分:0)

看起来你已经在实现了SelectElement类,所以你试过这个

WebElement element = getElementByName(name);
element.FindElement(By.CssSelector("option[value='" + value + "']").Select();

答案 2 :(得分:0)

使用以下代码在“国家/地区”中选择一个值。列表(一旦&#39;国家&#39;值被选中,相应的&#39;州&#39;列表正在加载):

WebElement selectCountry = driver.findElement(By.id("country"));
List<WebElement> options = selectCountry.findElements(By.tagName("option"));
for(WebElement option : options){
    if(option.getText().equalsIgnoreCase("India")){
        option.click();
        break;
    }
}

注意 - 与FF相比,此选择操作需要更多时间IE。您可能需要使用driver.manage()来增加命令超时时间。