【问题标题】:Get text without tags from web page using Jsoup使用 Jsoup 从网页获取不带标签的文本
【发布时间】:2016-09-14 15:13:26
【问题描述】:

我必须使用 Jsoup 从网页中提取一些数据。

我已经轻松提取了标签中包含的数据,但我仍然需要一些没有标签的数据。

这是 HTML 源代码的示例:

<a id="aId" href="aLink" style="aStyle">
    <span id="spanId1">
        <b>Caldan Therapeutics</b> 
        Announces Key Appointments And A Collaboration With 
        <b>Sygnature Discovery</b>  
    </span>
    <span id="spanId2" style="spanStyle2">
        5/17/2016
    </span>
</a>

我已经提取了&lt;b&gt;标签中包含的数据以及日期,但我现在想要的是提取句子Announces Key Appointments And A Collaboration With

如你所见,这句话没有标签。

我可以做些什么来提取它?

我已经完成了我的研究,我所能找到的只是如何去除所有标签。

感谢您的帮助!

【问题讨论】:

  • 我已经看到了,它所做的只是去除 html 标签。这不是我想要的。我想要的是只提取未标记的句子Announces Key Appointments And A Collaboration With

标签: java jsoup


【解决方案1】:

我找到了针对该特定需求的答案,我想与将来可能面临同样问题的任何人分享。

你所能做的就是使用函数ownText(),它会从元素的子标签中排除文本。

在我们的例子中:

public static void main(String[] args) throws Exception {
    Document doc = Jsoup.connect("http://source-url").get();
    Elements spanTags = doc.getElementsByTag("span");
    for (Element spanTag : spanTags) {
        String text = spanTag.ownText();
        System.out.println(text);
    }
}

【讨论】:

  • 请将此标记为答案。在 StackOverflow 上,回答和标记你的答案并不被认为是坏事。 ;)
【解决方案2】:

您也可以使用以下代码执行此操作,但它会将您的文本作为字符串返回,将段落替换为“\n”,并且不允许您检测文本样式(如粗体、斜体等)。

如果你只想获取纯文本,这真的很有用:

Element aElem = doc.getElementById("spanId1");
String yourText = aElem.wholeText();

如果您使用 aId 作为元素的 ID,您还将获得 spanId2 的内容,并且无法轻松判断文本的哪一部分是日期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多