【问题标题】:HTML parsing and extracting textHTML解析和提取文本
【发布时间】:2023-03-04 23:48:01
【问题描述】:

有许多资源可以解析 HTML 页面和提取文本内容。 Jsoup 就是一个例子。就我而言,我想提取带有每个句子出现的 html 标记的文本内容。以这个页面为例

<html>
<head><title>Test Page</title>
<body>
<h1>This is a test page</h1>
<p> The goal is to extract <b>textual content <em> with html tags</em> </b> from html pages.
</body>
</html>

我希望输出是这样的:

<h1>This is a test page</h1>
<p> The goal is to extract <b>textual content <em> with html tags</em> </b> from html pages.

换句话说,我想在页面的文本内容中包含特定的 html 标签。

【问题讨论】:

    标签: html-parsing jsoup text-extraction


    【解决方案1】:

    要得到你的结果,你可以使用这个:

    final String html = "<html>"
            + "<head><title>Test Page</title>"
            + "<body>"
            + "<h1>This is a test page</h1>"
            + "<p> The goal is to extract <b>textual content <em> with html tags</em> </b> from html pages."
            + "</body>"
            + "</html>";
    
    // Parse the String into a Jsoup Document
    Document doc = Jsoup.parse(html);
    Elements body = doc.body().children();
    
    // Do further things here ...
    System.out.println(body);
    

    您也可以加载文件或网站,而不是字符串 html - jsoup 提供了这一切。

    在此示例中,body 包含您作为结果发布的 html。

    或者你需要选择“h1后跟p标签”之类的东西吗?

    不过你可以看看Jsoup Selector API

    【讨论】:

    • 谢谢你。这就是我所缺少的。
    【解决方案2】:

    您分两步完成。首先,正如您所描述的,使用 JSoup 创建一个 DOM 树。然后使用 XSL 过滤器对其进行处理。在 XSL 过滤器中,您只能提取那些您感兴趣的标签。

    【讨论】:

    • 这会递归工作吗?标签内的标签就像 p 标签内的 b 标签内的 em 标签一样?
    猜你喜欢
    • 2011-02-06
    • 1970-01-01
    • 2013-12-22
    • 2011-04-04
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多