LoginSignup
2
2

Docker で Selenium を動かす

Last updated at Posted at 2024-03-30

はじめに

ブラウザの自動操作を試してみたかったので、コンテナで環境を構築しました。
使用ブラウザは Chrome で Python の Selenium を採用しています。

フォルダ構成

.
├── app.py
├── docker-compose.yml
├── Dockerfile
└── requirements.txt

Dockerfile

FROM python:3

RUN sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' && \
    wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - && \
    apt update && \
    apt install google-chrome-stable -y

COPY app.py .
COPY requirements.txt .

RUN pip install --upgrade -r requirements.txt

CMD ["python", "app.py"]

Chrome を apt コマンドでインストールします。
Python パッケージは requirements.txt を参照して pip 経由でインストールします。

requirements.txt

selenium-wire
chromedriver-binary-auto

pip でインストールする python パッケージは管理しやすいように requirements.txt に記述しておきます。

今回は HAR ファイルも取得するようにしたかったため、selenium を拡張するパッケージである selenium-wire ライブラリを使用します。
HAR ファイルはブラウザのネットワークアクティビティを記録したものとなります。

ChromeDriver はインストールしている Chrome のバージョンに合わせる必要があります。
chromedriver-binary-auto パッケージを入れれば自動でインストールされている Chrome のバージョンに合わせたものをインストールしてくれるので便利です。

docker-compose.yml

HAR ファイルの保存場所として、ローカル端末の harfile ディレクトリをマウントしておきます。

version: '3'
services:
  chrome-selenium:
    build:
      context: .
      dockerfile: Dockerfile
    volumes:
      - ./harfile:/home/harfile

app.py

今回はサンプルなので、阿部寛の HP にアクセスしておきます。

from seleniumwire import webdriver
from selenium.webdriver import ChromeOptions
import chromedriver_binary

options = ChromeOptions()
options.add_argument("--headless")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")

sw_options = {
    'enable_har': True
}

url = "http://abehiroshi.la.coocan.jp/"

driver = webdriver.Chrome(options=options, seleniumwire_options=sw_options)
driver.get(url)

print(driver.title)
print(driver.current_url)

with open('/home/harfile/test.har', mode='w') as f:
    f.write(driver.har)

driver.quit()

動作確認

docker compose build でビルドしたあとに、起動してみます。
指定した URL にアクセスして、タイトルが取得できています。

$ docker compose up
[+] Running 1/0
 ✔ Container test-chrome-selenium-1  Created                           
Attaching to test-chrome-selenium-1
test-chrome-selenium-1  | 阿部寛のホームページ
test-chrome-selenium-1  | http://abehiroshi.la.coocan.jp/

ローカル端末の harfile ディレクトリに test.har が作成されています。
HAR ファイルはブラウザの開発者ツールに読み込ませると内容が簡単に確認できます。
ブラウザからどのような通信が行われているのか確認できます。
指定した URL に GET リクエストを行って、関連したファイルも取得していることを確認できました。

スクリーンショット 2024-03-25 170250.png

おわりに

今回は環境構築を行ったので、次回は何かしらのサイトの UI 自動化を試してみたいと思います。
ログインが必要なサイトの認証の突破とかを試したいなと考えています。

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