บทนำ
ตัวอย่างนี้แสดงวิธีดึงและแยกข้อมูลจากหน้าเว็บ (Web Scraping) โดยใช้ Library Jsoup ใน Android
ขั้นตอนที่ 1: สร้างโปรเจกต์
สร้างโปรเจกต์ Android ใหม่ใน Android Studio
ขั้นตอนที่ 2: เพิ่ม Dependency (build.gradle)
dependencies {
implementation 'org.jsoup:jsoup:1.17.2'
}
ขั้นตอนที่ 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="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="Fetch Website" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/btnParseHTML"
android:layout_marginTop="16dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/background_dark"
android:textSize="12sp"
android:textStyle="bold" />
</ScrollView>
</RelativeLayout>
ขั้นตอนที่ 4: MainActivity.kt
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() {
private lateinit var button: Button
private lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "HTML Parser"
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: $title\n\n")
for (link in links) {
stringBuilder.append("Link: ${link.attr("href")}\n")
stringBuilder.append("Text: ${link.text()}\n\n")
}
} catch (e: IOException) {
stringBuilder.append("Error: ${e.message}\n")
}
runOnUiThread { textView.text = stringBuilder.toString() }
}).start()
}
}
ขั้นตอนที่ 5: Manifest (ต้องมี Internet Permission)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.htmlparser">
<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>
Jsoup Selectors ที่ใช้บ่อย
| Selector | คำอธิบาย |
|---|---|
tag | เลือกตามชื่อแท็ก เช่น div, a |
.class | เลือกตาม CSS class เช่น .header |
#id | เลือกตาม ID เช่น #main |
[attr] | เลือกที่มี attribute เช่น [href] |
[attr=value] | เลือกที่ attribute เท่ากับค่า |
parent > child | ลูกโดยตรง |
ancestor descendant | ลูกชายหน้าทุกระดับ |
ตัวอย่าง Selector 進階
// ตารางข้อมูล
val rows = doc.select("table.data-table tr")
// ข้อความใน div ที่มี class content
val content = doc.select("div.content").text()
// รูปภาพทั้งหมด
val images = doc.select("img[src]")
for (img in images) {
val src = img.attr("src") // URL รูป
val alt = img.attr("alt") // Alt text
}
แนวทางปฏิบัติที่ดี (Best Practices)
- ใช้ Coroutines แทน Thread แบบเดิม (Modern approach)
- เพิ่ม User-Agent เพื่อไม่ถูกบล็อก
- จัดการ Timeout และ Error handling ให้ครบถ้วน
- เคารพ robots.txt และ Terms of Service ของเว็บไซต์
- พิจารณาใช้ API อย่างเป็นทางการถ้ามีให้