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

วิธี Parse HTML ใน Android ด้วย Jsoup

ภาพรวม

ตัวอย่างนี้สาธิตวิธีการ Parse (แยกวิเคราะห์) HTML จากเว็บไซต์ใน Android โดยใช้ไลบรารี Jsoup

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

เปิด Android Studio → File → New Project → กรอกรายละเอียดที่จำเป็น

ขั้นตอนที่ 2: จัดทำ Layout (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="12sp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnParseHTML"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ดึงข้อมูลเว็บไซต์"
        android:layout_marginTop="40dp"
        android:layout_centerHorizontal="true" />

    <TextView
        android:id="@+id/textView"
        android:text="ผลลัพธ์"
        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: เพิ่ม Dependency Jsoup ใน build.gradle (Module: app)

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

ขั้นตอนที่ 4: เขียนโค้ด MainActivity (src/MainActivity.java)

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 {
                    // เชื่อมต่อและดึง HTML
                    Document doc = Jsoup.connect("https://www.tutorialspoint.com/").get();

                    // ดึง Title
                    String title = doc.title();
                    stringBuilder.append(title).append("\n");

                    // ดึง Link ทั้งหมด (a[href])
                    Elements links = doc.select("a[href]");
                    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");
                }

                // อัปเดต UI บน Main Thread
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText(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.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>

Jsoup Selectors ที่นิยมใช้

Selector คำอธิบาย
tagname เลือกโดย Tag เช่น div, span
#id เลือกโดย ID เช่น #main-content
.class เลือกโดย Class เช่น .article-body
[attribute] เลือกโดย Attribute เช่น a[href]
parent > child Child ตรงๆ เช่น ul > li
ancestor descendant Descendant เช่น .container .item

การทดสอบ

รันแอปบนอุปกรณ์จริง (ต้องมีอินเทอร์เน็ต) กดปุ่ม "ดึงข้อมูลเว็บไซต์\" จะแสดง Title และ Links

วิธี Parse HTML ใน Android ด้วย Jsoup

แนะนำ: ใช้ Coroutines + OkHttp + Jsoup แทน Thread แบบเก่า สำหรับโค้ดที่ทันสมัยและจัดการ Error ได้ดีกว่า