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

Kotlin으로 안드로이드에서 HTML 파싱하는 방법 – Jsoup 활용 완벽 가이드

이 튜토리얼에서는 KotlinJsoup 라이브러리를 사용하여 안드로이드 앱에서 웹페이지의 HTML을 파싱하는 방법을 단계별로 살펴봅니다. 버튼 하나를 누르면 지정한 웹사이트의 제목과 모든 링크를 가져와 화면에 출력하는 간단한 예제를 만들어 보겠습니다.

1단계: 새 프로젝트 생성

Android Studio에서 File → New Project를 선택하고, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.

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

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 버튼과 결과를 표시할 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="8dp"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/btnParseHTML"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="Get website" />
    <TextView
        android:textColor="@android:color/background_dark"
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnParseHTML"
        android:layout_centerHorizontal="true"
        android:text="Result"
        android:textSize="12sp"
        android:textStyle="bold" />
</RelativeLayout>

3단계: Jsoup 의존성 추가

build.gradle (Module: app) 파일의 dependencies 블록에 아래 의존성을 추가합니다.

implementation 'org.jsoup:jsoup:1.11.2'

Jsoup은 Java/Kotlin 환경에서 HTML을 손쉽게 파싱하고 조작할 수 있도록 도와주는 대표적인 오픈소스 라이브러리입니다.

4단계: MainActivity.kt 작성

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

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements
import java.io.IOException
class MainActivity : AppCompatActivity() {
    lateinit var button: Button
    lateinit var textView: TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        textView = findViewById(R.id.textView)
        button = findViewById(R.id.btnParseHTML)
        button.setOnClickListener {
            getHtmlFromWeb()
        }
    }
    private fun getHtmlFromWeb() {
        Thread(Runnable {
            val stringBuilder = StringBuilder()
            try {
                val doc: Document = Jsoup.connect("https://www.tutorialspoint.com/").get()
                val title: String = doc.title()
                val links: Elements = doc.select("a[href]")
                stringBuilder.append(title).append("\n")
                for (link in links) {
                    stringBuilder.append("\n").append("Link : ")
                        .append(link.attr("href")).append("\n").append("Text : ").append(link.text())
                }
            } catch (e: IOException) {
                stringBuilder.append("Error : ").append(e.message).append("\n")
            }
            runOnUiThread { textView.text = stringBuilder.toString() }
        }).start()
    }
}

5단계: 인터넷 권한 설정

androidManifest.xml 파일에 인터넷 접근 권한을 추가해야 합니다. 이 권한이 없으면 네트워크 요청 시 오류가 발생합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.q11">
    <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 아이콘을 클릭하세요. 실행 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 앱이 실행됩니다.

버튼을 누르면 해당 웹사이트의 페이지 제목과 함께 문서 내 모든 링크의 URL과 텍스트가 TextView에 순서대로 표시됩니다. 네트워크 연결에 실패하면 오류 메시지가 출력됩니다.