Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

Web Scraping ในแอปพลิเคชัน Android ด้วย Kotlin

ภาพรวม

ตัวอย่างนี้สาธิตการดึงข้อมูลจากเว็บไซต์ (Web Scraping) ใน Android โดยใช้ไลบรารี Jsoup และทำงานใน Background Thread ด้วย AsyncTask (Deprecated) ควรใช้ Coroutines ในโปรเจกต์จริง

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio เลือก File → New Project

ขั้นตอนที่ 2: เพิ่ม Dependency (build.gradle)

dependencies {
    implementation "org.jsoup:jsoup:1.17.2"
    // หรือเวอร์ชันล่าสุดจาก Maven Central
}

ขั้นตอนที่ 3: 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="16dp"
    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="8dp"
        android:text=""
        android:textSize="14sp" />

    <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="25dp"
        android:text="Scrap Text from Web" />

</RelativeLayout>

ขั้นตอนที่ 4: MainActivity.kt (ใช้ AsyncTask - แบบเก่า)

import android.os.AsyncTask
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import org.jsoup.Jsoup
import java.io.IOException

@Suppress("DEPRECATION")
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 {
            WebScratch().execute()
        }
    }

    @Suppress("DEPRECATION")
    inner class WebScratch : AsyncTask<Void, Void, String?>() {
        override fun doInBackground(vararg params: Void): String? {
            return try {
                val document = Jsoup.connect("https://www.tutorialspoint.com/css_online_training/index.asp").get()
                document.text()
            } catch (e: IOException) {
                e.printStackTrace()
                null
            }
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            textView.text = result ?: "Failed to load data"
        }
    }
}

วิธีการทำงานสมัยใหม่ (Coroutines + Jsoup)

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
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 text = document.text()
                    withContext(Dispatchers.Main) {
                        textView.text = text
                    }
                } catch (e: Exception) {
                    withContext(Dispatchers.Main) {
                        textView.text = "Error: ${e.message}"
                    }
                }
            }
        }
    }
}

ขั้นตอนที่ 5: Manifest

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

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

    <application ... >
        <activity android:name=".MainActivity"> ... </activity>
    </application>
</manifest>

หมายเหตุสำคัญ

  • AsyncTask ถูก Deprecated ตั้งแต่ API 30 ควรใช้ Coroutines + Flow หรือ RxJava
  • Jsoup ทำงานแบบ Synchronous ต้องรันบน IO Thread (Dispatchers.IO)
  • ปฏิบัติตาม robots.txt และ Terms of Service ของเว็บไซต์เป้าหมาย
  • ควรจัดการ Error handling และ Timeout ให้เหมาะสม
  • สำหรับ Production ควรใช้ Retrofit + OkHttp สำหรับ API แทน Scraping HTML

การทดสอบ

รันแอป กดปุ่ม "Scrap Text from Web" ข้อความจากเว็บไซต์จะแสดงใน TextView