Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 HTML 파싱하는 방법 – Jsoup 라이브러리 완벽 가이드

이 튜토리얼에서는 안드로이드 앱에서 Jsoup 라이브러리를 사용하여 웹페이지의 HTML을 파싱하는 방법을 단계별로 알아봅니다. 버튼 클릭 시 특정 웹사이트에 접속해 페이지 제목과 모든 링크를 추출해 화면에 표시하는 예제입니다.

1단계: 새 프로젝트 생성

Android Studio를 열고 File → New Project 메뉴로 이동한 후, 필요한 모든 정보를 입력하여 새 프로젝트를 생성합니다.

2단계: 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면에는 HTML 파싱을 시작할 버튼과 결과를 표시할 TextView가 배치됩니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="12sp"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/btnParseHTML"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get website"
        android:layout_marginTop="40dp"
        android:layout_centerHorizontal="true"/>
    <TextView
        android:id="@+id/textView"
        android:text="Result"
        android:textSize="12sp"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnParseHTML"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

3단계: Jsoup 의존성 추가

HTML 파싱을 위해 build.gradle (Module: app) 파일의 dependencies 블록에 다음 의존성을 추가합니다.

implementation 'org.jsoup:jsoup:1.11.2'

의존성을 추가한 후 반드시 Sync Now를 클릭해 Gradle 동기화를 완료하세요.

4단계: MainActivity 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. 네트워크 작업은 메인 스레드에서 수행할 수 없으므로 별도의 백그라운드 스레드에서 실행하고, 결과는 runOnUiThread()를 통해 UI에 반영합니다.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
    Button button;
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        button = findViewById(R.id.btnParseHTML);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getHtmlFromWeb();
            }
        });
    }
    private void getHtmlFromWeb() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final StringBuilder stringBuilder = new StringBuilder();
                try {
                    Document doc = Jsoup.connect("https://www.tutorialspoint.com/").get();
                    String title = doc.title();
                    Elements links = doc.select("a[href]");
                    stringBuilder.append(title).append("\n");
                    for (Element link : links) {
                        stringBuilder.append("\n").append("Link : ").append(link.attr("href")).append("\n").append("Text : ").append(link.text());
                    }
                } catch (IOException e) {
                    stringBuilder.append("Error : ").append(e.getMessage()).append("\n");
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText(stringBuilder.toString());
                    }
                });
            }
        }).start();
    }
}

주요 코드 설명

  • Jsoup.connect(url).get(): 지정한 URL에 접속하여 HTML 문서를 가져옵니다.
  • doc.title(): 페이지의 제목 태그 값을 추출합니다.
  • doc.select("a[href]"): 문서 내 모든 링크(a 태그) 요소를 선택합니다.
  • link.attr("href"): 각 링크의 href 속성값을 가져옵니다.

5단계: 인터넷 권한 설정

웹에 접속하려면 androidManifest.xml 파일에 인터넷 권한을 반드시 선언해야 합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하세요. 실행 옵션에서 자신의 모바일 기기를 선택하면, 기본 화면이 표시됩니다.

안드로이드에서 HTML 파싱하는 방법 – Jsoup 라이브러리 완벽 가이드

버튼을 누르면 지정한 웹사이트의 제목과 함께 해당 페이지에 포함된 모든 링크의 URL과 텍스트가 TextView에 나타납니다. 이처럼 Jsoup을 활용하면 몇 줄의 코드만으로도 손쉽게 HTML을 파싱하고 원하는 데이터를 추출할 수 있습니다.