有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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) 个答案

  1. # 1 楼答案

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

    其次,您似乎认为getAllSelectedOptions()将返回为所有<select>字段选择的所有选项。事实并非如此。相反,它只返回单个<select>字段的所有选定选项。这只有在使用multiple属性时才有意义

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

  2. # 2 楼答案

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

    List<WebElement> selectedOpts = driver.findElements(
             By.cssSelector("select.form-control > option:checked"));
    
    for(WebElement temp : selectedOpts ) {
          System.out.println(temp.getText());
    }