Java通过Jsoup解析Html

Java通过Jsoup解析Html

从HTML文件中解析需要的数据,通常使用正则匹配可以实现,也可以使用Jsoup实现

Jsoup官网:https://jsoup.org/

maven

maven项目在pom.xml中引入jsoup依赖包

        <dependency>
            <!-- jsoup HTML parser library @ https://jsoup.org/ -->
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.14.3</version>
        </dependency>

简单使用

jsoup不仅可以处理HTML页面文件或内容,同时也支持HTMl的字段,可以更加需要直接解析其中文本,也可以解析指定标签中的内容

从HTML中获取文本内容

所有的HTML标签都去除,文本内容通过空格拼接

    public static void testStr(){

        String html = "<ol class=\" list-paddingleft-2\" style=\"width: 758.094px; white-space: normal;\">" +
                "<li><p>第一段</p></li>" +
                "<li><p>第二段</p></li>" +
                "<li><p>第三段</p></li></ol>" +
                "<ul class=\" list-paddingleft-2\" style=\"width: 758.094px; white-space: normal;\">" +
                "<li><p>111</p></li>" +
                "<li><p>222</p></li>" +
                "<li><p>333</p></li>" +
                "<li><p>444<br/></p></li>" +
                "</ul><p><br/></p>";
        Document document = Jsoup.parse(html);
        String resultView = document.text();
        System.out.println("resultView:" + resultView);
    }

解析出文本内容

    resultView:第一段 第二段 第三段 111 222 333 444
从HTML中获取指定标签内容
    public static void testFile(){
        File file = new File("D:\\MyProject\\fileStorage\\response.html");
        try {
            Document document = Jsoup.parse(file, "utf-8");
            /* 解析内容
           <td width="670">
                <table class="resultView" width="95%" height="60" align="center" cellspacing="0">
                    <tbody class="resultTBody">
                        <tr align="center">
                            <td width="20%">
                                抱歉!没有查询到相关记录。
                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
            */

            // 获取 class="resultView" 标签中内容
            String resultView = document.select("table[class=resultView]").html();
            System.out.println("resultView:" + resultView);

            String text = document.select("table[class=resultView]").text();
            System.out.println("text:" + text);

        } catch (IOException e) {
            System.out.println(e);
        }
    }

解析出文本内容

resultView:<tbody class="resultTBody"> 
 <tr align="center"> 
  <td width="20%"> 抱歉!没有查询到相关记录。 </td> 
 </tr> 
</tbody>

text:抱歉!没有查询到相关记录。
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值