본문 바로가기

Android

[Android] jsoup를 이용하여 파싱 하기

안드로이드 앱에서 크롤링 혹은 데이터 파싱을 하기 위해서 jsoup를 많이 사용하게 된다.

jsoup의 사용법을 간단하게 알아보자.

설치

https://jsoup.org/download

 

Download and install jsoup

Download and install jsoup jsoup is available as a downloadable .jar java library. The current release version is 1.13.1. What's new See the 1.13.1 release announcement for the latest changes, or the changelog for the full history. Previous releases of jso

jsoup.org

 

위에서 jsoup를 다운로드하자.

다운로드한 jsoup를 안드로이드 프로젝트 폴더의 app\libs 경로에 추가한다.

우측 상단에서 보는 방법을 Project로 변경한 후

jsoup를 추가한 경로를 가서 우 클릭 Add As Library 클릭.

<uses-permission android:name="android.permission.INTERNET" />

AndroidManifest.mxl에서 퍼미션 코드 추가를 하면 끝이다.

사용

 

try{
  Document   doc = Jsoup.connect("http://naver.com").get();
}catch (IOException e) {
   e.printStackTrace();
   Log.d("test","Error: "+e.toString());
}
Elements lis= doc.select("body");
String tmp="";
for(Element li : lis)
{
   tmp = tmp + li.text()+"\n";
}

Log.d("test","ok:"+ tmp);

네이버의 html 코드를 가지고 와서 li 태그를 기준으로 모두 출력하는 모습.

에러 부분

java.io.IOException: Cleartext HTTP traffic to www.google.com not permitted

이 에러는 HTTP는 이제 사용할 수 없다는 에러이다.

해결 방법

1. HTTPS 사용

2. HTTP 허용시키기.

android:usesCleartextTraffic="true"

또 이렇게 해도 안된다면

Jsoup를 사용할 때 스레드를 사용해보자.