LoginSignup
35

More than 1 year has passed since last update.

[Python]docker-selenium環境 構築方法 メモ

Last updated at Posted at 2021-06-12
  • 環境依存しないスクレイピング/E2Eテスト環境を作りたかったため、docker-seleniumの利用方法を調べた。その備忘録記事。

docker-selenium

  • Selenium

    • Web アプリケーションをテストするためのフレームワーク。
    • 各種 Web ブラウザに対する操作を自動化することができる。
  • docker-selenium

    • SeleniumをDocker環境で動かすためのイメージ

構成

docker-selenium.png

コード

ディレクトリ構成

ルート	- 	app	----- text --- test.py 
	  |			|__ Dockerfile
	  |			|__ requirements.txt
	  |__ docker-compose.yml			

docker-compose.yml

version: "3"
services:
  selenium:
    image: selenium/standalone-chrome-debug:3.2.0-actinium
    ports:
      - 4444:4444
      - 5900:5900
  app:
    build: ./app
    volumes:
      - ./app:/app
    environment:
      SELENIUM_URL: http://selenium:4444/wd/hub
    tty: true
    volumes:
      - /dev/shm:/dev/shm

Dockerfile

  • Python実行環境設定。依存ライブラリインストール含む。
FROM python:3.7

ENV PYTHONIOENCODING utf-8

WORKDIR /app

COPY . .

RUN pip install -r requirements.txt

requirements.txt

  • 依存ライブラリ定義
selenium

test.py

  • seleniumでGoogle検索した結果の1番目のタイトルを表示するコード。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import presence_of_element_located
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import os

if __name__ == '__main__':
    # Selenium サーバーへ接続する。
    driver = webdriver.Remote(
        command_executor=os.environ["SELENIUM_URL"],
        desired_capabilities=DesiredCapabilities.CHROME.copy()
    )
    # 任意のHTMLの要素が特定の状態になるまで待つ
    # ドライバとタイムアウト値を指定
    wait = WebDriverWait(driver, 10)
    # Googleにアクセス
    driver.get("https://google.com")
    # "selenium"で検索
    driver.find_element(By.NAME, "q").send_keys("selenium" + Keys.RETURN)
    # 1件目の検索結果を取得(描画されるまで待機)
    first_result = wait.until(
        presence_of_element_located((By.CSS_SELECTOR, "h3")))
    print(first_result.get_attribute("textContent"))

    driver.quit()

動作確認

  • ビルド→起動→コンテナの中に入る。
docker-compose build --no-cache
docker-compose up -d
docker-compose exec app bash
  • コード実行
cd test
python test.py

期待値:10分で理解する Selenium - Qiitaのように検索結果が表示される。

参考情報

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
35