jszt 的个人博客 jszt 的个人博客

记录精彩的程序人生

目录
对java智能化解析html Boilerpipe包的简单了解
/    

对java智能化解析html Boilerpipe包的简单了解

前几天看到一个博客https://cuiqingcai.com/6454.html,里面介绍了一些智能化解析html的工具,我对Boilerpipe还蛮感兴趣的,就想今天来试一下;

我是用maven构建的项目,但Boilerpipe好像maven仓库中没有;
我就在google下了一个1.2.0的版本,加到了我的本地仓库里;

仓库.png

然后导入pow.xml

<dependency>
    <groupId>de.l3s.boilerpipe</groupId>
    <artifactId>boilerpipe</artifactId>
    <version>1.2.0</version>
</dependency>
<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.13</version>
</dependency>

接下来就是写代码了

import de.l3s.boilerpipe.document.TextDocument;

import de.l3s.boilerpipe.extractors.ArticleExtractor;

import de.l3s.boilerpipe.sax.BoilerpipeSAXInput;
import de.l3s.boilerpipe.sax.HTMLDocument;
import de.l3s.boilerpipe.sax.HTMLFetcher;

import java.net.URL;

public class Application {
    public static void main(String[] args) throws Exception {
        String url = "http://jsjianwang.cn/articles/2019/03/19/1552968344762.html";
        HTMLDocument htmlDoc = HTMLFetcher.fetch(new URL(url));
        TextDocument doc = new BoilerpipeSAXInput(htmlDoc.toInputSource()).getTextDocument();
        String title = doc.getTitle();
        System.out.println("标题:        "+title);
        String content = ArticleExtractor.INSTANCE.getText(doc);

        System.out.println("正文:     "+content);
    }
}

运行结果如下:

运行结果.png

但是这只是简单页面的解析;

复杂的页面好像是无法自动解析的,比如https://news.ifeng.com/c/7kQcQG2peWU
结果.png

但是可以获取到html代码,这样就可以手动解析了(但这样就没有必要用到Boilerpipe了)

	String url = "https://news.ifeng.com/c/7kQcQG2peWU";

        HTMLDocument htmlDoc = HTMLFetcher.fetch(new URL(url));
        TextDocument doc = new BoilerpipeSAXInput(htmlDoc.toInputSource()).getTextDocument();

        String title = doc.getTitle();
        System.out.println("标题:        "+title);
        String content = ArticleExtractor.INSTANCE.getText(doc);
        System.out.println("内容:     "+content);
        //得到html
        byte[] html = htmlDoc.getData();
        System.out.println(new String(html));

结果

结果.png

参考资料:
https://www.cnblogs.com/endless-on/p/3503996.html