如何从所有表中获取元素,并且每个表都不要选择嵌套表我想从id = customers,customers2,customers3中选择表但问题是customers3嵌套在customers2中我不是想要使用获取ID和客户2没有任何客户3项请帮助并谢谢
PS。最简单的方法,你可以尝试在网络https://try.jsoup.org/ 示例文件: https://github.com/jhy/jsoup/files/403482/Table01.txt PS。小姐带我去问这里
答案 0 :(得分:0)
在我花了很多时间后,我找到了获得的方法,但它仅适用于1个嵌套表,代码看起来很脏(我已使用此文件进行了测试https://github.com/jhy/jsoup/files/403482/Table01.txt)
StringBuilder contentBuilder = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new
FileReader(System.getProperty("user.dir")+"\\html\\"+"Table01.html"));
String str;
while ((str = in.readLine()) != null) {
contentBuilder.append(str);
}
in.close();
} catch (IOException e) {
}
String html = contentBuilder.toString();
Document doc = Jsoup.parse(html);
// Take nested table as Elements first
Elements nestedTables = doc.select("td table");
// remove nested Table in document
doc.select("td table").remove();
// Then get it again
Elements tables = doc.select("table");
这是尽我所能。 非常感谢,Davide Pastore 对不起英语
答案 1 :(得分:0)
听起来你有一个包含这样的表的页面:
<table id="customers">
<tr>
<td>foo1</td>
<td>bar1</td>
</tr>
</table>
<table id="customers2">
<tr>
<td>foo2</td>
<td>bar2</td>
<td>
<table id="customers3">
<tr>
<td>foo3</td>
<td>bar3</td>
</tr>
</table>
</td>
</tr>
</table>
你想获得元素,不包括嵌入元素。
您可以使用CSS选择器来完成此任务。
for (Element cell : doc.select("table td:not(:has(table))"))
System.out.println(e.ownText());
<强>输出强>
foo1
bar1
foo2
bar2
foo3
bar3
此外,您不需要使用缓冲区打开文件并获取jsoup的所有文本内容。您只需将文件传递给Jsoup即可。
Document doc = Jsoup.parse(new File("test.html"), "UTF-8");
有关更多示例,请参阅Jsoup Cookbook。