LoginSignup
2
2

More than 1 year has passed since last update.

kotlin×seluniumでスクレイピング

Posted at

環境

  • Windows 10 Home
  • kotlin 1.5.30
  • Google Chrome 94.0

webdriverダウンロード

まずPCのGoogle Chromeのバージョンを確認します。
image.png
ここでは94.0.4606.61となっています。

webdriverをダウンロードします。
https://chromedriver.chromium.org/downloads
image.png
ここではメジャーバージョンがPCのChromeと一致している「ChromeDriver 94.0.4606.41」を選択してダウンロードします。

ダウンロードしたzipファイルを展開してできたファイルを任意のフォルダに配置します。

gradle設定

build.gradle.kts

dependencies {
    implementation("org.seleniumhq.selenium:selenium-java:3.141.59")
    implementation("org.seleniumhq.selenium:selenium-support:3.141.59")
}

コード

Scraping.kt
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions

fun main(args: Array<String>) {
    // 環境変数にchromedriverのパスを設定(自身の環境に合わせて設定してください)
    System.setProperty("webdriver.chrome.driver", "C:\\tool\\chromedriver_win32\\chromedriver.exe")

    val options = ChromeOptions().apply {
        // headlessモードにする場合はここで指定
        addArguments("--headless")
    }

    val driver: WebDriver = ChromeDriver(options)
    // Webページにアクセス
    driver.get("https://ja.wikipedia.org/wiki/ウェブスクレイピング")
    // pタグの最初の要素を取得
    val p = driver.findElements(By.tagName("p"))[0]
    // コンソールにテキストを出力
    println(p.text)

    // ブラウザを閉じる
    driver.close()
}

結果

Starting ChromeDriver 94.0.4606.41 (333e85df3c9b656b518b5f1add5ff246365b6c24-refs/branch-heads/4606@{#845}) on port 6418
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
9 27, 2021 2:37:43 午後 org.openqa.selenium.remote.ProtocolHandshake createSession
情報: Detected dialect: W3C
ウェブスクレイピング(英: Web scraping)とは、ウェブサイトから情報を抽出するコンピュータソフトウェア技術のこと。通常このようなソフトウェアプログラムは低レベルのHTTPを実装することで、もしくはウェブブラウザを埋め込むことによって、WWWのコンテンツを取得する。ウェブスクレイピングはユーザーが手動で行なうこともできるが、一般的にはボットやクローラ(英: Web crawler)を利用した自動化プロセスを指す。

プロセスは終了コード 0 で終了しました
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2