1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

第2回:Seleniumの基本操作とChromeDriverの導入方法【準備編】

Posted at

🧠 Seleniumとは?

Seleniumは、Webブラウザをプログラムで自動操作するためのツールです。
人間がブラウザでやっている「クリック」「入力」「スクロール」などを、Pythonコードで再現できます。


🛠️ 開発環境のセットアップ

まずはPythonの仮想環境を作ってライブラリを管理しましょう。

# 仮想環境作成(例: venv)
python -m venv venv
source venv/bin/activate  # Windowsなら venv\Scripts\activate

# 必要ライブラリのインストール
pip install selenium python-dotenv

🚀 ChromeDriverの導入:自動化バージョン

通常、ChromeDriverは手動でダウンロードしてパスを通す必要がありますが、Chromeのバージョンが更新されるたびにエラーが発生しやすく、非常に厄介です

そこで今回は、webdriver-manager を使って、Pythonコード内でChromeDriverを自動インストール&バージョン管理できるようにします。


一応ダウンロードして実行する手順も記載しておく。

🧩 ChromeDriverの導入手順

Seleniumはブラウザを操作するために「WebDriver」というソフトを必要とします。今回は Google Chrome用のChromeDriver を使います。

導入ステップ:
  1. Chromeのバージョン確認
    chrome://settings/help にアクセスして確認。

  2. 対応するChromeDriverをダウンロード
    公式サイト:https://googlechromelabs.github.io/chrome-for-testing/
    StableのBinary:chrome driverで各プラットフォームを実行環境に適したものをダウンロード

  3. ダウンロードしたZIPを解凍し、chromedriver.exe をプロジェクトフォルダに配置。
    または、パスが通っているフォルダに置く。


💻 Seleniumの基本操作例(Python)

from selenium import webdriver
from selenium.webdriver.common.by import By

# ChromeDriverを指定して起動
driver = webdriver.Chrome()

# ページを開く
driver.get("https://example.com")

# 要素を取得してクリック
button = driver.find_element(By.ID, "submit-button")
button.click()

# あとは焼くなり煮るなり
# テキストを取得
text = driver.find_element(By.CLASS_NAME, "title").text
print(text)

# 終了
driver.quit()

🐛 トラブルシューティング

🛠️ よくあるエラーとその解決方法

❌ 要素が見つからない(find_element

画面の読み込みが終わる前に要素を取得しようとして、NoSuchElementException が発生することがあります。
その場合は 明示的な待機処理(WebDriverWait を入れることで解決できます。

✅ 修正前

button = driver.find_element(By.ID, "submit-button")

✅ 修正後

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.ID, "submit-button"))
)

このように element_to_be_clickable を使うと、「要素が表示されていて、クリックできる状態になるまで待つ」 という処理になります。

🔍 element_to_be_clickable は、「その要素が表示されていて、かつ有効(enabled)であるか」を確認して返してくれる便利な条件式です。


❌ ブラウザが勝手に閉じる

スクリプトの最後に driver.quit() を書いていると、処理がすぐに終わってブラウザが一瞬で閉じてしまうことがあります。

✅ 解決策

確認のためにしばらく待機する処理を入れておくと便利です:

def wait_for_user(msg="🔴 Enterを押すと続行します:"):
    input(msg)

wait_for_user()  # 必要な場面で呼び出す
driver.quit()

次回は:
第3回:実際に「空き状況を取得する」処理を書いてみよう! を予定しています!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?