如何用Java高效地解析HTML?
我在工作中进行了大量的 HTML 解析。到目前为止,我一直在使用 HtmlUnit 无头浏览器进行解析和浏览器自动化。
现在,我想将这两个任务分开。
我想使用轻量级 HTML 解析器,因为在 HTMLUnit 中首先加载页面,然后获取源代码,然后解析它需要花费很多时间。
我想知道哪个 HTML 解析器可以有效地解析 HTML。我需要
- Speed
- Ease 通过“id”或“名称”或“标签类型”来定位任何 HtmlElement。
如果它不清除脏的 HTML 代码,那对我来说就没问题了。我不需要清理任何 HTML 源代码。我只需要最简单的方法来移动 HtmlElements 并从中获取数据。
I do a lot of HTML parsing in my line of work. Up until now, I was using the HtmlUnit headless browser for parsing and browser automation.
Now, I want to separate both tasks.
I want to use a light HTML parser because it takes much time in HTMLUnit to first load a page, then get the source, and then parse it.
I want to know which HTML parser can parse HTML efficiently. I need
- Speed
- Ease to locate any HtmlElement by its "id" or "name" or "tag type".
It would be ok for me if it doesn't clean the dirty HTML code. I don't need to clean any HTML source. I just need the easiest way to move across HtmlElements and harvest data from them.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
jsoup
自插件:我刚刚发布了一个新的 Java HTML 解析器:jsoup。我在这里提到它是因为我认为它会做你所追求的事情。
它的技巧是使用 CSS 选择器语法来查找元素,例如:
请参阅 Selector< /a> javadoc 了解更多信息。
这是一个新项目,因此非常欢迎任何改进的想法!
jsoup
Self plug: I have just released a new Java HTML parser: jsoup. I mention it here because I think it will do what you are after.
Its party trick is a CSS selector syntax to find elements, e.g.:
See the Selector javadoc for more info.
This is a new project, so any ideas for improvement are very welcome!
到目前为止我见过的最好的是 HtmlCleaner:
借助 HtmlCleaner,您可以使用 XPath 定位任何元素。
对于其他 html 解析器,请参阅这个问题。
The best I've seen so far is HtmlCleaner:
With HtmlCleaner you can locate any element using XPath.
For other html parsers see this SO question.
我建议使用Validator.nu的解析器,基于HTML5解析算法。 这是 Mozilla 从 2010 年 5 月 3 日开始使用的解析器
I suggest Validator.nu's parser, based on the HTML5 parsing algorithm. It is the parser used in Mozilla from 2010-05-03