Jsoup在带有多个标签的标签后选择文本

时间:2018-10-22 07:05:56

标签: java jsoup extract

我想使用jsoup在每个文本之后提取一个文本。有什么办法可以选择吗?

示例代码如下:

<div class="content">
<div name="panel-summary" id="summary">
    <p>
    <strong>A: </strong>*thank you* **I want to retrieve this text**<br>
    <strong>B: </strong>*Bla..bla* *I don't want this text*<br>
    <strong>C: </strong>*what ever text* *I dont want this*                         
        <strong>D: </strong>*anythinh text* *I want this*<br>
        <strong>E: </strong>*Bla..bla* *I don't want this text*t<br>
        <strong>F: </strong>*anythinh text* *I want this*<br>
    </p>

    <p>I want this</p>

,完成后会创建自动id示例id = 123

1 个答案:

答案 0 :(得分:0)

如果我们可以假设您要查找的所有<strong>元素将始终包含A:D:F:,则使用strong:matchesOwn(regex)(其中regex将代表A:|D:|F:),我们可以选择这些元素。

处理strong之后,我们可以移至第二个<p>并通过text()获取其文本内容。

String html = "<div class=\"content\">\n" +
        "<div name=\"panel-summary\" id=\"summary\">\n" +
        "    <p>\n" +
        "    <strong>A: </strong>*thank you* **I want to retrieve this text**<br>\n" +
        "    <strong>B: </strong>*Bla..bla* *I don't want this text*<br>\n" +
        "    <strong>C: </strong>*what ever text* *I dont want this*                         \n" +
        "        <strong>D: </strong>*anythinh text* *I want this*<br>\n" +
        "        <strong>E: </strong>*Bla..bla* *I don't want this text*t<br>\n" +
        "        <strong>F: </strong>*anythinh text* *I want this*<br>\n" +
        "    </p>\n" +
        "\n" +
        "    <p>I want this</p>";

Document doc = Jsoup.parse(html);
Elements pElements = doc.select("#summary p");
Elements strongElements = pElements.first().select("strong:matchesOwn(A:|D:|F:)");
for (Element strong : strongElements) {
    System.out.println(strong.nextSibling());//get next element, including textual element
}
System.out.println("---");
System.out.println(pElements.get(1).text());//textual content of <p>I want this</p>

输出:

*thank you* **I want to retrieve this text**
*anythinh text* *I want this*
*anythinh text* *I want this*
---
I want this

如果您不想依靠<strong>的内容,而只是依靠其索引,则可以像

一样选择所有索引
Elements allStrElemens = doc.select("#summary p strong");

并通过它们的索引(请记住索引从0开始)中选择所需的那些,例如

System.out.println(allStrElemens.get(0).nextSibling());
System.out.println(allStrElemens.get(3).nextSibling());
System.out.println(allStrElemens.get(5).nextSibling());