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

Web Scraping trong ứng dụng Android với Jsoup

Hướng dẫn này trình bày 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. Jsoup là thư viện Java phổ biến để parse HTML, trích xuất và thao tác dữ liệu từ trang web.

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 và điền thông tin cần thiết.

Bước 2: Thêm dependency Jsoup (build.gradle Module:app)

dependencies {
    // ... các dependency khác
    implementation 'org.jsoup:jsoup:1.11.2'
}

Lưu ý: Phiên bản 1.11.2 là phiên bản cũ. Khuyến nghị sử dụng phiên bản mới nhất (ví dụ 1.17.2 hoặc mới hơn) để đảm bảo bảo mật và tương thích.

Bước 3: 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"
    tools:context=".MainActivity">

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

    <Button
        android:id="@+id/btnView"
        android:text="Cào dữ liệu từ web"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="25sp"
        android:layout_alignParentBottom="true"/>

</RelativeLayout>

Bước 4: Code MainActivity (src/MainActivity.java)

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    TextView textView;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        button.setOnClickListener(v -> new DoItTask().execute());
    }

    // AsyncTask để chạy network operation trên background thread
    private class DoItTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... params) {
            try {
                // Kết nối và tải HTML từ URL
                Document document = Jsoup.connect("https://www.tutorialspoint.com/css_online_training/index.asp").get();
                // Trích xuất toàn bộ text (bỏ thẻ HTML)
                return document.text();
            } catch (IOException e) {
                e.printStackTrace();
                return "Lỗi: " + e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            textView.setText(result);
        }
    }
}
Quan trọng: Android cấm thực hiện network operation trên main thread (UI thread). Phải dùng AsyncTask, Thread, ExecutorService, hoặc thư viện hiện đại như Coroutines / RxJava / Retrofit.

Bước 5: Cấu hình quyền Internet (AndroidManifest.xml)

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

    <!-- Quyền truy cập Internet BẮT BUỘC -->
    <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 "Cào dữ liệu từ web" - ứng dụng sẽ tải trang web, trích xuất text và hiển thị.

Web Scraping trong ứng dụng Android với Jsoup

Mở rộng và lưu ý

  • Selector CSS: Jsoup hỗ trợ selector mạnh mẽ: doc.select("div.content > p"), doc.select("a[href]")
  • User-Agent: Một số trang chặn request không có User-Agent: Jsoup.connect(url).userAgent("Mozilla/5.0...").get()
  • Timeout: Thiết lập timeout: .timeout(10000) (10 giây)
  • AsyncTask đã deprecated (API 30+): Nên dùng ExecutorService, Coroutines hoặc RxJava
  • Tuân thủ robots.txt và điều khoản dịch vụ của trang web