Android
 Computer >> コンピューター >  >> プログラミング >> Android

KotlinでAndroidアプリにWebスクレイピング機能を実装する方法

この記事では、Kotlinを使用してAndroidアプリケーション内でWebスクレイピングを行う方法を、実際のコード例とともに解説します。HTMLの取得・解析には、Java/Kotlin向けの定番ライブラリ「Jsoup」を活用します。

事前準備:Jsoupライブラリの依存関係を追加

Jsoupを使うには、まずappレベルのbuild.gradleのdependenciesブロックに以下の行を追加して、プロジェクトを同期(Sync)してください。

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

ステップ1:新規プロジェクトの作成

Android Studioを開き、「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。

ステップ2:レイアウトファイル(activity_main.xml)の編集

res/layout/activity_main.xmlに以下のコードを記述します。画面下部にボタンを配置し、その上にスクレイピング結果を表示するTextViewを設置しています。

<?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>

ステップ3:MainActivity.ktの実装

src/MainActivity.ktに以下のコードを追加します。ボタンがタップされると、AsyncTaskの内部クラスがバックグラウンドスレッドでJsoupを使って指定URLのHTMLを取得し、ページ全体のテキストを抽出してTextViewに表示する仕組みです。

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
    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()
        }
    }
    inner class WebScratch : AsyncTask<Void, Void, Void>() {
        private lateinit var words: String
        override fun doInBackground(vararg params: Void): Void? {
            try {
                val document = Jsoup.connect("https://www.tutorialspoint.com/css_online_training/index.asp").get()
                words = document.text()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return null
        }
        override fun onPostExecute(aVoid: Void?) {
            super.onPostExecute(aVoid)
            textView.text = words
        }
    }
}
ポイント:ネットワーク通信はメインスレッドでは行えないため、AsyncTaskやコルーチンなどを使ってバックグラウンドで処理する必要があります。なお、AsyncTaskは現在非推奨(Deprecated)となっているため、最新のプロジェクトではコルーチンやWorkManagerの利用が推奨されます。

ステップ4:AndroidManifest.xmlへの権限追加

インターネット通信を行うため、androidManifest.xmlに以下のように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>

アプリの実行と動作確認

それでは、アプリを実行してみましょう。実機のAndroidスマートフォンをPCに接続していることを前提に説明します。Android Studioからアプリを起動するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。表示された選択肢から接続中のモバイルデバイスを選択すると、実機の画面にアプリが起動します。

ボタンをタップすると、指定したWebページのテキストが取得され、TextViewに表示されます。これで、KotlinとJsoupを使ったシンプルなWebスクレイピング機能の完成です。

  1. AndroidアプリでWebスクレイピングを実装する方法【Jsoupライブラリ活用】

    この記事では、AndroidアプリケーションでWebスクレイピングを行う方法を、HTML解析ライブラリ「Jsoup」を使用した具体的なサンプルコードとともに段階的に解説します。Webページからテキストデータを取得して画面に表示するまでの一連の流れを学べます。AndroidでのWebスクレイピングの仕組みAndroidでWebページの内容を取得するには、ネットワーク通信をバックグラウンドで実行する必要があります。本記事のサンプルでは、非同期処理のためのAsyncTaskクラスと、HTMLの取得・解析を簡単に行えるJsoupライブラリを組み合わせて実装します。実装手順ステップ1:新規プロジェクトを

  2. Pythonのlxmlライブラリを使ったWebスクレイピングの実装方法を解説

    本記事では、Pythonで利用できるlxmlモジュールを使用したWebスクレイピングの手法について解説します。 Webスクレイピングとは? Webスクレイピングとは、クローラーやスキャナーと呼ばれるプログラムを使って、Webサイトからデータを取得する技術のことです。APIを提供していないWebページからデータを抽出したい場合に特に便利な手法です。 Pythonでは、Webスクレイピングを行うためのモジュールが複数用意されており、代表的なものとして「Beautiful Soup」「Scrapy」「lxml」などが挙げられます。 本記事では、その中でもlxmlモジュールを使ったスクレイピング方法を