无法使用 jsoup 表单元素设置选择选项 HTML



试图使用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>

用于在上面选择选项中设置性别的J汤格式:

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

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

注释中的解释:

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());

您需要设置要拾取的选项的selected属性。完整示例见此答案:

Jsoup POST:定义一个返回HTML的选定选项?

最新更新