Jsoup选择并迭代所有元素 [英] Jsoup select and iterate all elements
问题描述
我将通过jsoup连接到一个url并获取它的所有内容但是如果我选择的话就是这样,
I will connect to a url through jsoup and get all the contents of it but the thing is if I select like,
doc.select("body")
返回单个元素,但我希望得到所有页面中的元素并逐个迭代它们,例如,
its returning a single element but I want to get all the elements in the page and iterate them one by one for example,
<html>
<head><title>Test</title></head>
<body>
<p>Hello All</p>
<a href="test.html">Second Page</a>
<div>Test</div>
</body>
</html>
如果我选择使用正文,我会在一行中得到结果,如
If I select using body I am getting the result in a single line like,
Test Hello All Second Page Test
相反,我想要选择所有元素并逐个迭代并产生结果,例如,
Instead I want to select all elements and iterate one by one and produce the results like,
Test
Hello All
Second Page
Test
是否可以使用jsoup?
Will that be possible using jsoup?
谢谢,
Karthik
Thanks,
Karthik
推荐答案
您可以使用 *
选择器选择文档的所有元素,然后使用 Element#ownText()
单独获取每个元素的文本。
You can select all elements of the document using *
selector and then get text of each individually using Element#ownText()
.
Elements elements = document.body().select("*");
for (Element element : elements) {
System.out.println(element.ownText());
}
这篇关于Jsoup选择并迭代所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!