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

lkalay picture lkalay · Mar 25, 2011 · Viewed 18.7k times · Source

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?

Answer

Gagravarr picture Gagravarr · Apr 2, 2011

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.