链氪巴士
  1. 首页
  2. 站点导航
  3. 文章
  4. 快讯
  5. 软件
  6. 书刊
  7. 关于
Featured image of post 【源码】Java 如何去除字符串中的 HTML 标签

【源码】Java 如何去除字符串中的 HTML 标签

使用爬虫爬取网站数据,有时会将 HTML 相关的标签也一并获取,如何将这些无关的标签去除呢?源码如下。

背景

使用爬虫爬取网站数据,有时会将 HTML 相关的标签也一并获取,如何将这些无关的标签去除呢?

源码

package com.demo.nlp;

import java.util.regex.Pattern;

class CleanHtmlUtil {

    public static void main(String[] args) {
        String htmlStr = "<h2 class=\"wp-block-heading\"><span id=\"i-2\">当前有效的激活方式介绍</span></h2>\r\n"
        		+ "<p>目前只有三种方式:<strong>JB Account、Activation Code</strong> 和 <strong>License server</strong>。</p>\r\n"
        		+ "<h3 class=\"wp-block-heading\"><span id=\"JB_Account\">JB Account</span></h3>\r\n"
        		+ "<p>作为学生,该账号自然是通过教育邮箱取得授权。如果大学没有提供 edu.cn 邮箱的可以通过学信网,联系 JetBrains 进行授权。万能的淘宝也能买到,商家会提供一个(例如 <a href=\"https://xuanyuan.me/blog/wp-content/themes/wordpress-theme-puock-2.8.11/inc/go.php?to=aHR0cHM6Ly93d3cuamV0YnJhaW5zLmNvbS9zaG9wL2Vmb3JtL3N0dWRlbnRzL3JlcXVlc3Q/Y29kZT0=\" target=\"_blank\" rel=\"noreferrer noopener\">https://www.jetbrains.com/shop/eform/students/request?cod</a><a href=\"https://xuanyuan.me/blog/wp-content/themes/wordpress-theme-puock-2.8.11/inc/go.php?to=aHR0cHM6Ly9ibG9nLm5haXhpLm5ldC9hSFIwY0hNNkx5OTNkM2N1YW1WMFluSmhhVzV6TG1OdmJTOXphRzl3TDJWbWIzSnRMM04wZFdSbGJuUnpMM0psY1hWbGMzUV9ZMjlrWlQw\" target=\"_blank\" rel=\"noreferrer noopener\">e=</a> )的链接,然后让你点击登录账号后激活即可。</p>\r\n"
        		+ "<div class=\"wp-block-image\">\r\n"
        		+ "<figure class=\"aligncenter size-large\"><img title=\"2024 最新 JetBrains IDEA 激活教程 (11月27更新)\"\r\n"
        		+ "             alt=\"2024 最新 JetBrains IDEA 激活教程 (11月27更新)\" decoding=\"async\" data-src=\"https://sourcecodebeat.com:557/2024/blog/10/1024/xuanyuan.me-3292920975.361gungd09.webp\" data-lazy=\"true\" src=\"https://xuanyuan.me/blog/wp-content/themes/wordpress-theme-puock-2.8.11/assets/img/z/load.svg\" alt=\"2024 最新 JetBrains 全家桶激活教程 (IntelliJ IDEA)\" title=\"lkb5nxzy.png\"/></figure>\r\n"
        		+ "</div/>";

        String cleanedHtml = removeHtmlTags(htmlStr);
        System.out.println(cleanedHtml);
    }

    private static String removeHtmlTags(String html) {
        if (html == null || html.isEmpty()) {
            return "";
        }

        String regex = "<script[^>]*?>[\\s\\S]*?<\\/script>|<style[^>]*?>[\\s\\S]*?<\\/style>|<[^>]+>|\\s+| ?";
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

        return pattern.matcher(html)
                .replaceAll("")
                .trim();
    }
}

输出结果

当前有效的激活方式介绍目前只有三种方式:JBAccount、ActivationCode和Licenseserver。JBAccount作为学生,该账号自然是通过教育邮箱取得授权。如果大学没有提供edu.cn邮箱的可以通过学信网,联系JetBrains进行授权。万能的淘宝也能买到,商家会提供一个(例如https://www.jetbrains.com/shop/eform/students/request?code=)的链接,然后让你点击登录账号后激活即可。
使用 Hugo 构建
主题 Stack,作者 Jimmy