Github ActionsでSeleniumを実行する(自動テスト)
背景
seleniumというソフトを利用すると、Chromeブラウザを起動してPythonなどのプログラムで制御してテストを実行できます。
これをGithubActionsで実行して、自動的にブラウザによるテストを実装します。
ファイル構成
.github/workflows/run.yaml
selenium/main.py
selenium/requirements.txt
.github/workflows/run.yamlはGithubActionsの内容が記載されています。
selenium/requirements.txtはPython環境で依存しているモジュールが記載されています。
selenium/main.pyにテストコードが入っている感じです
github actions
name: selenium-github-actions
on: [push]
jobs:
selenium:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: '3.8'
architecture: 'x64'
- run: |
pip install get-chrome-driver --upgrade
pip install -r selenium/requirements.txt
python selenium/main.py
こちらのファイルではGithubActionsの内容が記載されています。
注目する部分はactions/setup-python@v2というコミュニティアクションを取得して、Pythonの実行環境を整えています。
次のrunの部分で実際に動かすコードを記載しています。
pip install get-chrome-driver --upgrade
pip install -r selenium/requirements.txt
python selenium/main.py
get-chrome-driverというモジュールをインストールしています。これはseleniumでChromeを操作するためのドライバを用意してくれるモジュールです。
※通常はchromedriver-binaryというものを利用するのですが、これがChromeのバージョンによって異なるバージョンを用意する必要があります。get-chrome-driverはchromedriver-binaryを「現在インストールしているChromeのバージョンを確認してインストールしてくれる」モジュールになります。
pip install -r selenium/requirements.txtはrequirements.txtに記載されたモジュールをインストールする処理で、python selenium/main.pyはテストを実行する処理になります。
Python
requirements.txtではseleniumをインストールしています。
#chromedriver-binary==92.0.4515.107.0
selenium==3.141.0
main.pyではseleniumを利用して、私のサイトにアクセスして、タイトルの一部を取得してみます。
この部分をテストです。
(対象のWebサイトをテストする場合は、何らかの方法をサイトを起動してアクセスさせる必要があります。)
from get_chrome_driver import GetChromeDriver
from selenium import webdriver
get_driver = GetChromeDriver()
get_driver.install()
def driver_init():
options = webdriver.ChromeOptions()
options.add_argument('--headless')
return webdriver.Chrome(options=options)
driver = driver_init()
driver.get('https://hashito.biz/')
print(driver.find_element_by_xpath('/html/body/div[1]/div/section/div/div/h2').text)
print(driver.current_url)
driver.quit()
Discussion