`<div class="col1">
<strong>
<select name="Category" multiple size="4">
<option value="A">A
<option value="B" selected>B
<option value="C">C
<option value="D">D
</select></strong>
</div>`
Run Code Online (Sandbox Code Playgroud)
我有一个包含上面给出的下拉列表的 div 类,我只需要使用 Jsoup 从下拉列表中获取“选定”项的值
搜索<select>元素,遍历它的子元素并检查该selected属性是否存在:
Document doc = Jsoup.parse("your html")
String selectedVal = null;
Elements options = doc.getElementsByAttributeValue("name", "Category").get(0).children();
for (Element option : options) {
if (option.hasAttr("selected")) {
selectedVal = option.val();
}
}
Run Code Online (Sandbox Code Playgroud)
或者简而言之,使用类似 CSS 的选择器:
String selectedVal = doc.select("select[name=Category] option[selected]").val();
Run Code Online (Sandbox Code Playgroud)