Java

[Java] Jsoup 라이브러리

콩스프 2022. 12. 10. 23:45

Jsoup 이란?

  • real-world HTML을 다루기위한 Java 라이브러리
  • URL을 fetch하고 HTML5 DOM의 method 와 CSS selector를 사용하여 데이터를 추출 및 처리하는 편리한 API를 제공

 

  • URL, 파일, 문자열을 통해 HTML을 파싱할 수 있음
String html = "<html><head><title>First parse</title></head>"
            + "<body><p>Parsed HTML into a doc.</p></body></html>";

Document doc = Jsoup.parse(html);

 

parse(String html, String baseUri)
인자로 들어온 html을 파싱하는 메소드

- html : 파싱하기위한 HTML
- baseUri : 상대경로를 절대경로로 확인하기위해 사용되는 argument
parse(String html)

 

 

 

  • DOM traversal 또는 CSS selector를 통해 데이터를 찾고 추출
File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");

Elements links = doc.select("a[href]"); // a with href
Elements pngs = doc.select("img[src$=.png]");
  // img with src ending .png

Element masthead = doc.select("div.masthead").first();
  // div with class=masthead

Elements resultLinks = doc.select("h3.r > a"); // direct a after h3

 

Element.select(String selector)
- Elements 의 리스트를 return
- select 메소드는 Document, Element, Elements Class 에서 정의 되어 있음
selector : Jsoup이 제공하는 매칭되는 elements를 찾기위한 CSS (or jquery) selector 
Elements.select(String selector)

 

 

Selector Overview

tagname 태그이름을 통해 elements를 찾음  a
ns | tag 태그이름과 네임스페이스를 통해 elements를 찾음 fb|name
#id ID를 통해 elements를 찾음 #logo 
.class class 이름을 통해 elements를 찾음 .masthead
[attirbute] 해당 속성을 가지는 elements를 찾음 [href] 
[^attr] 속성의 접두사가 attr인 elements를 찾음 [^data-]
[attr=value] 속성의 값이 value인 elements를 찾음 [width=500] 
[attr^=value],
[attr$=value],
[attr*=value]
속성의 값이 value로 시작하거나, 끝나거나, 포함하는 elements를 찾음 [href*=/path/]
[attr~=regex] 해당 속성의 값이 regular expression과 일치하는 elements를 찾음 img[src~=(?!)\.(png|jpe?g)]

 

 

Selector Combination

el#id 해당 ID를 가지는 elements를 찾음 div#logo
el.class 특정 class의 elements를 찾음 div.masthead
el[attr] 해당 속성을 가진 elements를 찾음 a[href]
ancestor child 해당 조상의 해당 자식 elements를 찾음 .body p
body 블록 내에 있는 p
parent > child 해당 부모의 바로 아래에 있는 해당 자식 elements를 찾음 div.content > p
클래스가 content인 div의 직계 child p
siblingA + siblingB A element 바로 앞에 있는 형제 B를 찾음 div.head + div
siblingA ~ siblingX A element 앞에 있는 형제 X element를 찾음 h1 ~ p
el, el, el 여러개의 selector들을 그룹화 하여 그 selecor 중 어떤 것이라도 일치하는 elements를 찾음 div.masthead, div.log

 

 

  • HTML의 element, attribute, text를  조작할 수 있음
Element div = doc.select("div").first(); // <div></div>
div.html("<p>lorem ipsum</p>"); // <div><p>lorem ipsum</p></div>
div.prepend("<p>First</p>");
div.append("<p>Last</p>");
// now: <div><p>First</p><p>lorem ipsum</p><p>Last</p></div>

Element span = doc.select("span").first(); // <span>One</span>
span.wrap("<li><a href='http://example.com/'></a></li>");
// now: <li><a href="http://example.com"><span>One</span></a></li>

 

Element.html(String html) element의 내부를 비우고 인자로 넘긴 값으로 대체
Element.prepend(String first)
Element.append(String last)
HTML을 elements 내부의 시작부분 / 끝 부분에 추가
Element. wrap(String around) element의 바깥을 인자로 받은 태그로 감싸도록 함

 

 

참고문헌

1) jsoup.org