我有这段 HTML:
<td class="my class" >
<div class="content" style="margin-left:10px;">
<ul style="list-style-type: disc;">
<li><span>obj: blue</span></li>
<li><span>descr: red</span></li>
<li><span>double: yellow</span></li>
</ul>
</div>
</td>
我需要:
obj: blue
descr: red
double: yellow
我已经尝试过:
docDescription.select("my.class").text();
但它返回包含所有文本的 block 。我需要 3 个不同的部分(逐行)。
最佳答案
解决方案
docDescription.select("div > ul > li > span");
说明
您的文档无效,对于 JSoup 来说如下所示。 JSoup 总是尝试修复文档。在您的情况下,td
位于任何table
之外,因此它被删除。
<html>
<head></head>
<body>
<div class="content" style="margin-left:10px;">
<ul style="list-style-type: disc;">
<li><span>obj: blue</span></li>
<li><span>descr: red</span></li>
<li><span>double: yellow</span></li>
</ul>
</div>
</body>
</html>
代码
public static void main(String[] args) {
String html = "<td class=\"my class\" >\n" +
" <div class=\"content\" style=\"margin-left:10px;\">\n" +
" <ul style=\"list-style-type: disc;\">\n" +
" <li><span>obj: blue</span></li>\n" +
" <li><span>descr: red</span></li>\n" +
" <li><span>double: yellow</span></li>\n" +
" </ul>\n" +
" </div>\n" +
"</td>";
Elements select = Jsoup.parse(html).select("div > ul > li > span");
for (Element element : select) {
System.out.println(element.text());
}
}
结果
obj: blue
descr: red
double: yellow
关于java - Jsoup HTML 解析 - 复杂节点 [Java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21381683/