woong's

Jsoup 사용하기 본문

Develop/Android

Jsoup 사용하기

dlsdnd345 2016. 2. 13. 23:17
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Jsoup 사용하기

 

 

jsoup은 기본적으로 HTML형식의 string을 넘겨주면 자바에서 사용할 수 있는 DOM 객체로 만들어 주는 라이브러리


Jsoup 준비

http://jsoup.org/download 해당경로 에서 jar 파일 다운로드



해당 프로젝트에 jar 파일 추가




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
response = response.replace("<image>""<bookimg>").replace("</image>""</bookimg>");
                            Document document = Jsoup.parse(response);
                            Elements elements = document.select("item");
 
                            for (Element element : elements) {
 
                                Book book = new Book();
                                book.setTitle(element.getElementsByTag("title").iterator().next().text().replaceAll("<(/)?([a-zA-Z]*)(\\s[a-zA-Z]*=[^>]*)?(\\s)*(/)?>"""));
                                book.setAuthor(element.getElementsByTag("author").iterator().next().text());
                                book.setImg(element.getElementsByTag("bookimg").iterator().next().text());
                                book.setDescription(element.getElementsByTag("description").iterator().next().text()
                                        .replaceAll("<(/)?([a-zA-Z]*)(\\s[a-zA-Z]*=[^>]*)?(\\s)*(/)?>""")
                                        .replaceAll("&lt;""").replaceAll("&gt;"""));
                                bookList.add(book);
 


 통신을 통해 받아온 데이터를 Jsoup.parse() 함수를 통해 Document 로 만듭니다.

document 의 selector 를 통해서 html 에서의 사용할 태그를 지정합니다 .

ex) Elements elements = document.select("item");

 


지정한 태그 안의 값을 사용하기 위해 사용할 태그를 지정합니다 .

ex) element.getElementsByTag("author").iterator().next().text();



이렇게 지정하면 <item> 태그 안의 <author> 라는 값을 가져 올수 있습니다 .

이와 같이 html 데이터를 쉽게 가져올수있도록 도와주는 라이브러리가 Jsoup 이 되겠습니다 .



ps . 네이버 api 를 통해서 jsoup을 사용해보는 도중 <image><image/> <link></link> 등의 태그가 제대로 만들어 지지 않는 경우가 있습니다.

이경우에 다른문자로 치환해서 Document 에 담아 진행하였습니다 .

ex) response = response.replace("<image>", "<bookimg>").replace("</image>", "</bookimg>");

Document document = Jsoup.parse(response);



Jsoup input output 을 볼수 있는 홈페이지 입니다 .


 

 


Comments