How can I use the HTML parser with Apache Tika in Java to extract all HTML tags?

孤街浪徒 提交于 2019-12-20 10:10:52

问题


I download tika-core and tika-parser libraries, but I could not find the example codes to parse HTML documents to string. I have to get rid of all html tags of source of a web page. What can I do? How do I code that using Apache Tika?


回答1:


Do you want a plain text version of a html file? If so, all you need is something like:

        InputStream input = new FileInputStream("myfile.html");
        ContentHandler handler = new BodyContentHandler();
        Metadata metadata = new Metadata();
        new HtmlParser().parse(input, handler, metadata, new ParseContext());
        String plainText = handler.toString();

The BodyContentHandler, when created with no constructor arguments or with a character limit, will capture the text (only) of the body of the html and return it to you.




回答2:


You can also you Tika AutoDetectParser to parse any type of files such as HTML. Here is a simple example of that:

    try {
        InputStream input = new FileInputStream(new File(path));
        ContentHandler textHandler = new BodyContentHandler();
        Metadata metadata = new Metadata();
        AutoDetectParser parser = new AutoDetectParser();
        ParseContext context = new ParseContext();
        parser.parse(input, textHandler, metadata, context);
        System.out.println("Title: " + metadata.get(metadata.TITLE));
        System.out.println("Body: " + textHandler.toString());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (TikaException e) {
        e.printStackTrace();
    }


来源:https://stackoverflow.com/questions/5429814/how-can-i-use-the-html-parser-with-apache-tika-in-java-to-extract-all-html-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!