使用selenium webdriver从列表框中逐个选择所有选项

时间:2014-07-03 16:51:17

标签: selenium-webdriver

 ***HTML***
    <select id="type" class="dropdownValues" name="type">
    <option class="dropdownValues" selected="selected" value="00">All</option>
    <option class="dropdownValues" value="01">Car</option>
    <option class="dropdownValues" value="02">House</option>
    <option class="dropdownValues" value="03">Boat</option>
    <option class="dropdownValues" value="04">Plane</option>
    <option class="dropdownValues" value="05">Tree</option>
    <option class="dropdownValues" value="06">Land</option>
    </select>

我的代码

    Select selectBox = new Select(driver.findElement(By.id("type")));
    List<WebElement> selectOptions = selectBox.getOptions();
    for (WebElement temp : selectOptions) 
    {


     System.out.println(temp.getText());
        }

***输出显示7次  所有
 汽车  屋  船  平面  树  土地  所有  汽车     屋     船     平面     树     土地     所有     汽车     屋     船     平面     树     土地     所有     汽车     屋     船     平面     树     土地     所有     汽车     屋     船     平面     树     土地     所有     汽车     屋     船     平面     树     土地

I would like to itterate through each options 1 times  and select them.

2 个答案:

答案 0 :(得分:1)

public static void main(String[] args)
{
    WebDriver driver=new FirefoxDriver();
    driver.get("file:///D:/Programming%20Samples/SelectOptions.html");

    WebElement item=new WebDriverWait(driver,60)
                    .until(ExpectedConditions.elementToBeClickable(By.id("type")));
    Select listItem=new Select(item);
    for(Integer i=0;i<listItem.getOptions().size();i++)
    {
        listItem.selectByIndex(i);
        System.out.println(listItem.getFirstSelectedOption().getText()); //Just to make sure what is selected
    }
    driver.close();
}

答案 1 :(得分:0)

我不熟悉Java中的WebDriver,但在C#中你会做这样的事情:

foreach (var elem in selectOptions){
   elem.Click(); //or elem.SendKeys(Keys.Enter);
}

请参阅已经回答的a duplicate question

相关问题