【问题标题】:JSoup - Incrementing through Tags / ArraysJSoup - 通过标签/数组递增
【发布时间】:2013-07-29 09:38:09
【问题描述】:

使用 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.
....

【问题讨论】:

  • 发布示例数组值。
  • 我澄清了“预期结果”区域。这有帮助吗?

标签: java jsoup


【解决方案1】:

您可以使用HashMap 来存储每个divP 元素列表。 地图的每个键都可以是您可以赋予 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);
}

【讨论】:

  • 谢谢。我将在今天晚些时候尝试这个解决方案,让你知道会发生什么。
  • 我必须用 div id 修改 HTML 吗?不幸的是,我正在从另一个网站上抓取这些内容,所以我无法真正修改网站上的 HTML?
  • 您能否将类 (happy-div, sad-div,descend-div) 视为您的每个 div 的唯一类?如果是这样,您可以使用它们来代替 id,即使它不是一个理想的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-20
  • 1970-01-01
相关资源
最近更新 更多