无法使用 Jsoup Formelement 设置 Select 选项 HTML

Can't Set Select Option HTML with Jsoup Formelement

尝试使用 JSOUP fromelement 在 html 中设置 select 选项,但没有成功。

<select name="gender" id="gender" class="textfield" required="true">
<option value=""
>Select</option>
<option value="2">Male</option>
<option value="1">Female</option>
<option value="3">Other</option>
</select>

Jsoup 用于在上面 select 选项中设置性别的元素:

Element gender = loginForm.select("#gender").first();
        gender.attr("Male","2");

如果有人知道怎么做,请告诉我,谢谢。

您需要设置要选择的选项的 selected 属性。有关完整示例,请参阅此答案:

Jsoup POST: Defining a selected option to return HTML?

评论中的解释:

    String html = "<select name=\"gender\" id=\"gender\" class=\"textfield\" required=\"true\">"
            + "<option value=\"\">Select</option>"
            + "<option value=\"2\">Male</option>"
            + "<option value=\"1\">Female</option>"
            + "<option value=\"3\">Other</option>"
            + "</select>";

    Document doc = Jsoup.parse(html);

    // getting all the options
    Elements options = doc.select("#gender>option");

    // optional, listing of all options
    for (Element option : options) {
        System.out.println("label: " + option.text() + ", value: " + option.attr("value"));
    }

    // optional, find option with attribute "selected" and remove this attribute to
    // deselect it; it's not needed here, but just in case
    Element selectedOption = options.select("[selected]").first();
    if (selectedOption != null) {
        selectedOption.removeAttr("selected");
    }

    // iterating through all the options and selecting the one you want
    for (Element option : options) {
        if (option.text().equals("Male")) {
            option.attr("selected", "selected"); // select only Male
        }
    }

    // result html with selected option:
    System.out.println(doc.body());