주요 Java HTML 파서의 장단점은 무엇입니까? [닫은]
SO와 Google을 검색하면서 여러 당사자가 지속적으로 권장하는 몇 가지 Java HTML 파서가 있음을 발견했습니다. 불행히도 다양한 라이브러리의 강점과 약점에 대한 정보를 찾기는 어렵습니다. 나는 어떤 사람들이이 도서관들을 비교하고 그들이 배운 것을 공유 할 수 있기를 바라고 있습니다.
내가 본 것은 다음과 같습니다.
그리고 내가 놓친 주요 파서가 있다면 장단점에 대해서도 듣고 싶습니다.
감사!
일반
거의 모든 알려진 HTML 파서는 W3C DOM API (JAXP API의 일부, Java 처리를위한 Java API)를 구현하고 JAXP API에서 org.w3c.dom.Document
직접 사용할 수있는 지원을 제공합니다 . 주요 차이점은 일반적으로 해당 파서의 기능에서 찾을 수 있습니다. 대부분의 파서는 JTidy , NekoHTML , TagSoup 및 HtmlCleaner 와 같이 잘 구성되지 않은 HTML ( "tagsoup")을 어느 정도 용서하고 관대 합니다. 일반적으로 이러한 종류의 HTML 파서를 사용하여 HTML 소스를 "정돈"(예 : HTML-valid <br>
를 XML-valid로 대체 <br />
) W3C DOM 및 JAXP API를 사용하여 "일반적인 방법"으로 트래버스 할 수 있습니다.
튀어 나오는 유일한 것은 HtmlUnit 과 Jsoup 입니다.
HtmlUnit
HtmlUnit 은 완전히 고유 한 API를 제공하므로 웹 브라우저처럼 프로그래밍 방식으로 작동 할 수 있습니다. 즉, 양식 값을 입력하고 요소를 클릭하고 JavaScript를 호출합니다. HTML 파서 그 자체가 아닙니다. 실제 "GUI-less 웹 브라우저"및 HTML 단위 테스트 도구입니다.
so
Jsoup 은 또한 완전히 고유 한 API를 제공합니다. jQuery 와 같은 CSS 선택기를 사용하여 요소를 선택할 수 있으며 HTML DOM 트리를 탐색하여 관심있는 요소를 가져 오는 매끄러운 API를 제공합니다.
특히 HTML DOM 트리의 통과는 Jsoup의 주요 강점입니다. 함께 일한 사람들 org.w3c.dom.Document
은 verbose NodeList
와 Node
API를 사용하여 DOM을 통과하는 것이 얼마나 고통 스러운지 알고 있습니다. 사실, XPath
인생이 더 쉬워 지지만 여전히 또 다른 학습 곡선이며 여전히 장황 할 수 있습니다.
다음은 XPath와 함께 JTidy와 같은 "일반"W3C DOM 파서를 사용하여 질문의 첫 번째 단락과 모든 응답자의 이름을 추출하는 예제입니다 (관심없는 정보를 수집하는 데 코드가 필요했기 때문에 XPath를 사용하고 있습니다) 그렇지 않으면 유틸리티 / 도우미 메소드를 작성하지 않고 10 배 커질 것입니다.
String url = "http://stackoverflow.com/questions/3152138";
Document document = new Tidy().parseDOM(new URL(url).openStream(), null);
XPath xpath = XPathFactory.newInstance().newXPath();
Node question = (Node) xpath.compile("//*[@id='question']//*[contains(@class,'post-text')]//p[1]").evaluate(document, XPathConstants.NODE);
System.out.println("Question: " + question.getFirstChild().getNodeValue());
NodeList answerers = (NodeList) xpath.compile("//*[@id='answers']//*[contains(@class,'user-details')]//a[1]").evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < answerers.getLength(); i++) {
System.out.println("Answerer: " + answerers.item(i).getFirstChild().getNodeValue());
}
다음은 Jsoup과 정확히 동일한 방법을 보여주는 예입니다.
String url = "http://stackoverflow.com/questions/3152138";
Document document = Jsoup.connect(url).get();
Element question = document.select("#question .post-text p").first();
System.out.println("Question: " + question.text());
Elements answerers = document.select("#answers .user-details a");
for (Element answerer : answerers) {
System.out.println("Answerer: " + answerer.text());
}
차이점이 보입니까? 코드가 적을뿐만 아니라 웹 사이트 개발 및 / 또는 jQuery 사용과 같은 CSS 선택기에 익숙한 경험이 있으면 Jsoup도 비교적 쉽게 파악할 수 있습니다.
요약
각각의 장단점은 이제 충분히 명확해야합니다. 표준 JAXP API를 사용하여 트래버스하려면 먼저 언급 한 파서 그룹으로 이동하십시오. 꽤 많이 있습니다. 선택하는 기능은 제공하는 기능 (HTML을 쉽게 만드는 방법, 리스너 / 인터셉터 및 태그 별 클리너가 있습니까?) 및 라이브러리의 견고성 (얼마나 자주 업데이트 / 유지 보수 / 고정됩니까?)에 따라 선택할 수 있습니다. ). HTML을 단위 테스트하려면 HtmlUnit을 사용하십시오. 실제 요구 사항보다 더 많은 HTML에서 특정 데이터를 추출하려면 Jsoup을 사용하는 것이 좋습니다.
이 기사 는 다음 파서의 특정 측면을 비교합니다.
- NekoHTML
- JTidy
- TagSoup
- HTMLCleaner
It is by no means a complete summary, and it is from 2008. But you may find it helpful.
Add The validator.nu HTML Parser, an implementation of the HTML5 parsing algorithm in Java, to your list.
On the plus side, it's specifically designed to match HTML5, and at the heart of the HTML5 validator, so highly likely to match future browser's parsing behaviour to a very high degree of accuracy.
On the minus side, no browsers' legacy parsing works exactly like this, and as HTML5 is still in draft, subject to change.
In practice, such problems only affect obscure corner cases, and is for all practical purposes, an excellent parser.
I found Jericho HTML Parser to be very well written, kept up to date (which many of the parsers are not), no dependencies, and easy to use.
I'll just add to @MJB answer after working with most of the HTML parsing libraries in Java, there is a huge pro/con that is omitted: parsers that preserve the formatting and incorrectness of the HTML on input and output.
That is most parsers when you change the document will blow away the whitespace, comments, and incorrectness of the DOM particularly if they are an XML like library.
Jericho is the only parser I know that allows you to manipulate nasty HTML while preserving whitespace formatting and the incorrectness of the HTML (if there is any).
Two other options are HTMLCleaner and HTMLParser.
I have tried most of the parsers here for a crawler / data extraction framework I have been developing. I use HTMLCleaner for the bulk of the data extraction work. This is because it supports a reasonably modern dialect of HTML, XHTML, HTML 5, with namespaces, and it supports DOM, so it is possible to use it with Java's built in XPath implementation.
It's a lot easier to do this with HTMLCleaner than some of the other parsers: JSoup for example supports a DOM like interface, rather than DOM, so some assembly required. Jericho has a SAX-line interface so again it is requires some work although Sujit Pal has a good description of how to do this but in the end HTMLCleaner just worked better.
I also use HTMLParser and Jericho for a table extraction task, which replaced some code written using Perl's libhtml-tableextract-perl. I use HTMLParser to filter the HTML for the table, then use Jericho to parse it. I agree with MJB's and Adam's comments that Jericho is good in some cases because it preserves the underlying HTML. It has a kind of non-standard SAX interface, so for XPath processing HTMLCleaner is better.
Parsing HTML in Java is a surprisingly hard problem as all the parsers seem to struggle on certain types of malformed HTML content.
'Programing' 카테고리의 다른 글
popen에 대한 작업 디렉토리를 지정하는 방법 (0) | 2020.05.23 |
---|---|
모범 사례? (0) | 2020.05.23 |
indexOf ()와 search ()의 차이점은 무엇입니까? (0) | 2020.05.23 |
사전 키로 사용자 정의 유형의 객체 (0) | 2020.05.23 |
Eclipse Europa, Helios, Galileo의 차이점 (0) | 2020.05.23 |