使用 JSoup 框架,我尝试迭代下面的 div 并提取每个 <p>
中的文本。标签放入数组中。因为列表<div>
的和<p>
是无限长的,do/while 循环或 for 循环将是获取 <p>
中信息的首选方法。 。
我不知道如何迭代<div>
下面的标签,因为我不确定如何跟踪 <p>
的内容其中标签<div>
我正在存储到数组中。如果答案是显而易见的,我很抱歉,因为我对 Java 和一般编程有点陌生。
非常感谢您的帮助。请告诉我是否有任何我可以添加的内容会有所帮助。
示例 HTML(假设重复数百次):
<div class="happy-div"> // want everything within this div to be in one array element
<p>good text here.</p>
<p>More good Text here.</p>
<p>Some good stuff here.</p>
</div>
<div class="sad-div"> // want everything within this div to be in a separate array element
<p>Some unhappy text here.</p>
<p>More unhappy Text here.</p>
<p>Some unhappy stuff here.</p>
</div>
<div class="depressed-div"> // everything within this div to be in a separate array element
<p>Some melancholy text here.</p>
<p>More melancholy Text here.</p>
<p>Some melancholy stuff here.</p>
</div>
.... repeats hundreds of times
伪代码:
String[] arrayOfP;
for (int i = 0; i < numberOfDivs; i++)
{
arrayOfP[i] = doc.select("All of the text in the <p> tags within the div we've incremented to")
System.out.println(arrayOfP[i])
}
预期结果:
当打印字符串数组元素值的内容时,我希望看到这样的内容:
arrayofP[1] Some good text here. More good Text Here. Some good stuff here.
arrayofP[2] Some unhappy text here. More unhappy Text Here. Some unhappy stuff here.
arrayofP[3] Some melancholy text here. More melancholy Text Here. Some melancholy stuff here.
....
最佳答案
您可以使用 HashMap
来存储每个 div
的 P
元素列表。
map 的每个键都可以是一个可以赋予 div 的 id,值是 P
元素的列表。
例如:
<div id="id_1" class="happy-div">
<p>good text here.</p>
<p>More good Text here.</p>
<p>Some good stuff here.</p>
</div>
Map<String, List<String>> data = new HashMap<String, List<String>>();
Elements divs = doc.select("div");
for (Element div : divs ) {
List<String> pList = new ArrayList<String>();
Elements pElements = div.select("p");
for (Element pElement : pElements) {
pList.add(pElement.text());
}
data.put(div.attr("id"), pLists);
}
for (List<String> pList : data.values()) {
System.out.println(pList);
}
关于java - JSoup - 通过标签/数组递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17920613/