Selenium Web-driver从下拉菜单中按索引选择值

时间:2016-01-22 14:45:26

标签: java selenium selenium-webdriver

我正在创建一个测试来填写注册表单的前端,但是,我想点击下拉箭头选择值,然后检查所选值是否为预期值:我可以选择下拉列表中的值并输入值,但是,我遇到的问题是来检查所选值是否正确。代码和错误如下:

  driver.findElement(By.cssSelector("#dijit_form_Select_1 > tbody > tr > td.dijitReset.dijitRight.dijitButtonNode.dijitArrowButton.dijitDownArrowButton.dijitArrowButtonContainer > input")).click();


        WebElement Menuitem = driver.findElement(By.cssSelector("#dijit_MenuItem_6_text"));

        boolean click1 = true; 

                Menuitem.click();

                //Checks if drop down button is selected 
                click1 = Menuitem.isSelected();

                if(click1 == false){
                    System.out.println("DropDown Was Selected");
                }else {
                    System.out.println("DropDown was not clicked");
                }



                Select Menuitem6 = new Select(driver.findElement(By.id("dijit_form_Select_1")));   

                Menuitem6.selectByVisibleText("Mr");

                List<WebElement> list = Menuitem6.getOptions();

                for(int i=0;i<list.size();i++){
                    if(list.get(i).getText().equals(Menuitem6.getFirstSelectedOption().getText())){
                        System.out.println("The index of the selected option is: "+i);
                        break;
                        }

来自控制台的错误:org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "table"

所以问题显然是因为html元素是一个表而不是select,我该如何解决这个问题呢?

HTML代码:

<tr aria-selected="false" widgetid="dijit_MenuItem_6" aria-disabled="false" aria-label="Mr " id="dijit_MenuItem_6" style="-moz-user-select: none;" class="dijitReset dijitMenuItem" data-dojo-attach-point="focusNode" role="option" tabindex="-1">
    <td class="dijitReset dijitMenuItemIconCell" role="presentation">
        <span role="presentation" class="dijitInline dijitIcon dijitMenuItemIcon dijitNoIcon" data-dojo-attach-point="iconNode"></span>
    </td>
    <td id="dijit_MenuItem_6_text" class="dijitReset dijitMenuItemLabel" colspan="2" data-dojo-attach-point="containerNode,textDirNode" role="presentation">Mr</td>
    <td id="dijit_MenuItem_6_accel" class="dijitReset dijitMenuItemAccelKey" style="display: none" data-dojo-attach-point="accelKeyNode"></td>
    <td class="dijitReset dijitMenuArrowCell" role="presentation">
        <span data-dojo-attach-point="arrowWrapper" style="visibility: hidden">
            <span class="dijitInline dijitIcon dijitMenuExpand"></span>
            <span class="dijitMenuExpandA11y">+</span>
        </span>
    </td>

1 个答案:

答案 0 :(得分:0)

这似乎是断言所选值是正确的很多工作。

不是迭代所有选项,而是仅仅引用与选择时相同的元素并使用GetAttribute(&#34; Selected&#34;)== true。特别是,如果该选择函数正在处理该元素。