如何在 Java 中使用带有 Apache Tika 的 HTML 解析器来提取所有 HTML 标签? [英] How can I use the HTML parser with Apache Tika in Java to extract all HTML tags?
问题描述
我下载了 tika-core 和 tika-parser 库,但找不到将 HTML 文档解析为字符串的示例代码.我必须摆脱网页源的所有 html 标签.我能做什么?我如何使用 Apache Tika 进行编码?
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?
推荐答案
您需要纯文本版本的 html 文件吗?如果是这样,您所需要的只是:
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();
BodyContentHandler 在没有构造函数参数或字符限制的情况下创建时,将捕获 html 正文的文本(仅)并将其返回给您.
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.
这篇关于如何在 Java 中使用带有 Apache Tika 的 HTML 解析器来提取所有 HTML 标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!