Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Web Scraping trong ứng dụng Android bằng Kotlin (Jsoup)

Giới thiệu

Ví dụ này minh họa cách thực hiện Web Scraping (cào dữ liệu web) trong ứng dụng Android sử dụng thư viện Jsoup và AsyncTask (hoặc Coroutine hiện đại).

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project, điền thông tin.

Bước 2: Thêm dependency Jsoup

Trong file build.gradle (Module: app) thêm:

dependencies {
    implementation "org.jsoup:jsoup:1.17.2"
}

Sau đó Sync Now.

Bước 3: Giao diện (res/layout/activity_main.xml)

<?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="4dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/btnView"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp"
        android:padding="4dp"
        android:text="" />

    <Button
        android:id="@+id/btnView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="25sp"
        android:text="Scrap Text from web" />

</RelativeLayout>

Bước 4: MainActivity.kt (sử dụng Coroutine thay AsyncTask)

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import org.jsoup.Jsoup

class MainActivity : AppCompatActivity() {
    private lateinit var textView: TextView
    private lateinit var button: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        textView = findViewById(R.id.textView)
        button = findViewById(R.id.btnView)

        button.setOnClickListener {
            lifecycleScope.launch(Dispatchers.IO) {
                try {
                    val document = Jsoup.connect("https://www.tutorialspoint.com/css_online_training/index.asp").get()
                    val words = document.text()
                    withContext(Dispatchers.Main) {
                        textView.text = words
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    withContext(Dispatchers.Main) {
                        textView.text = "Error: ${e.message}"
                    }
                }
            }
        }
    }
}

Lưu ý: AsyncTask đã deprecated từ API 30. Nên dùng Kotlin Coroutines với lifecycleScope và Dispatchers.IO cho tác vụ mạng.

Bước 5: AndroidManifest.xml (thêm quyền Internet)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhấn nút "Scrap Text from web", nội dung trang web sẽ hiển thị trong TextView.