尝试使用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表单元素:
Element gender = loginForm.select("#gender").first();
gender.attr("Male","2");
如果有人知道怎么做,请让我知道,谢谢。
发布于 2018-07-29 02:21:18
评论中的解释:
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());
发布于 2018-07-28 23:33:50
您需要设置要选择的选项的selected
属性。有关完整的示例,请参阅此答案:
https://stackoverflow.com/questions/51572776
复制相似问题