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

前端 未结 2 1951
温柔的废话
温柔的废话 2021-02-03 14:05

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 p

2条回答
  •  礼貌的吻别
    2021-02-03 14:27

    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();
        }
    

提交回复
热议问题