Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 앱에서 웹 스크래핑 구현하기 – Jsoup 라이브러리 활용 가이드

이 글에서는 안드로이드 애플리케이션에서 웹 스크래핑(Web Scraping)을 구현하는 방법을 단계별로 살펴봅니다. 웹 스크래핑은 웹페이지에서 필요한 데이터를 자동으로 추출하는 기술로, 안드로이드 환경에서는 주로 Jsoup이라는 오픈소스 Java 라이브러리를 사용합니다.

1단계: 새 프로젝트 생성

Android Studio를 실행한 뒤 File → New Project를 선택하고, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.

2단계: Jsoup 의존성 추가

build.gradle(Module: app) 파일을 열고 아래 의존성을 추가합니다.

implementation 'org.jsoup:jsoup:1.11.2'

3단계: 레이아웃 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"
    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="Scrap Text from web"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="25sp"
        android:layout_alignParentBottom="true"/>
</RelativeLayout>

4단계: MainActivity 코드 작성

src/MainActivity.java 파일에 다음 코드를 추가합니다. 네트워크 작업은 메인 스레드에서 수행할 수 없으므로, AsyncTask를 사용해 백그라운드에서 웹페이지를 가져오고 완료 후 UI에 결과를 표시합니다.

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(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new doIT().execute();
            }
        });
    }
    public class doIT extends AsyncTask<Void,Void,Void> {
        String words;
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Document document = Jsoup.connect("https://www.tutorialspoint.com/css_online_training/index.asp").get();
                words = document.text();
            } catch (IOException e) {
                e.printStackTrace();
            } return null;
        }
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            textView.setText(words);
        }
    }
}

5단계: 인터넷 권한 설정

androidManifest.xml 파일에 다음 코드를 추가합니다. 네트워크 통신을 위해 INTERNET 권한 선언이 반드시 필요하다는 점을 잊지 마세요.

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

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run(실행) 아이콘을 클릭하세요. 실행 옵션에서 본인의 모바일 기기를 선택하면, 기기 화면에 앱이 실행됩니다.

버튼을 누르면 지정한 웹페이지의 텍스트가 백그라운드에서 스크래핑되어 TextView에 표시됩니다.

안드로이드 앱에서 웹 스크래핑 구현하기 – Jsoup 라이브러리 활용 가이드