如何使用getAllSelectedOptions从多个下拉列表中获取选定的选项

时间:2018-06-04 13:33:33

标签: java selenium

Select dropdown1 = new Select(driver.findElement(By.xpath("//html/body/div/div[2]/div/div/div//div//select")));
List<WebElement> drop1 = dropdown1.getAllSelectedOptions();
for(WebElement temp : drop1) {
      String drop_text = temp.getText();
      System.out.println(drop_text);
}

上面的xpath表示3个下拉字段。当我执行此代码时,我只在第一个下拉列表中获取所选文本。我需要做哪些更改才能从所有三个下拉字段中获取所选选项。

 **html code**

<div class="form-group">
        <label class="control-label col-md-4 col-sm-4" for="type-select">Category<span style="color:red">*</span></label>
        <div class="col-md-8 col-sm-8">
            <select defaultattr="4" class="form-control input-style mandatory" data-val="true" data-val-number="The field CategoryID must be a number." id="CategoryID" name="CategoryID"><option value="">--Select--</option>
<option value="1">Architectural Firm</option>
<option value="2">Interior Design Firm</option>
<option value="3">General Contractor</option>
<option selected="selected" value="4">2tec2 Sales Network</option>
<option value="5">Cleaning Company</option>
<option value="6">Commercial end user</option>
</select>

<div class="form-group">
        <label class="control-label col-md-4 col-sm-4" for="type-select">Company Status</label>
        <div class="col-md-8 col-sm-8">
            <select class="form-control input-style" id="ddlCompanyStatus">
                    <option selected="selected" value="1">Active</option>
                    <option value="0">Non Active</option>
            </select>

        </div>
    </div>
<div class="form-group">      

2 个答案:

答案 0 :(得分:1)

首先,调用findElement()仅返回HTML页面中的单个元素。为了获得与给定选择器匹配的所有元素,您需要调用findElements()

其次,您似乎认为getAllSelectedOptions()将返回为所有<select>字段选择的所有选项。不是这种情况。相反,它仅返回单个 <select>字段的所有选定选项。只有在使用multiple属性时才有意义。

要在每个<select>中获取所选选项,首先需要使用findElements()而不是findElement()。然后,您需要遍历所选元素并在每个元素上调用getSelectedOption()

答案 1 :(得分:1)

您可以使用css选择器option:checked来获取所选选项

List<WebElement> selectedOpts = driver.findElements(
         By.cssSelector("select.form-control > option:checked"));

for(WebElement temp : selectedOpts ) {
      System.out.println(temp.getText());
}
相关问题