GitHub ActionsからSeleniumを実行する
概要
今回はGitHub ActionsでSeleniumを実行する方法について調べたので,メモを残しておきます.
実装したコードは,こちらに公開してあります.
環境構築
今回使用する環境は以下の通りです.
pyproject.toml
というファイルを作成し,以下を記述してください.
[tool.poetry] name = "selenium_gh_actions" version = "0.1.0" description = "" authors = ["Your Name <you@example.com>"] [tool.poetry.dependencies] python = "^3.9" selenium = "^4.1.0" chromedriver-binary = "96.0.*" [tool.poetry.dev-dependencies] [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api"
このpyproject.toml
ファイルから,GitHub Actions上で依存パッケージのインストールを実行します.
Seleniumのサンプルコードを用意する
今回はseleniumの動作確認ができればいいため,以下の簡単なスクリプトを使用します.
import chromedriver_binary from selenium import webdriver from selenium.webdriver.chrome.options import Options def main() -> None: options = Options() options.add_argument("--headless") driver = webdriver.Chrome(options=options) driver.get("https://google.com") print(f"Current ULR: {driver.current_url}") if __name__ == "__main__": main()
GitHub Actionsのワークフローを設定する
それではGitHub Actionsのワークフローを設定していきたいと思います.
大まかなワークフローの流れは以下です.
今回chromedriverのインストールには,以下のアクションを利用いたしました.
setup-chromedriver · Actions · GitHub Marketplace
name: run_selenium on: workflow_dispatch: jobs: run_selenium: name: run_selenium runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v2 # set up chrome driver - name: Setting up chrome driver uses: nanasess/setup-chromedriver@v1 with: chromedriver-version: '96.0.4664.45' # set up python - name: Setting up python. uses: actions/setup-python@v1 with: python-version: 3.9 # install poetry - name: Install Poetry run: | curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python - name: Add path for Poetry run: echo "$HOME/.poetry/bin" >> $GITHUB_PATH # install prod dependencies - name: Install dependencies run: poetry install --no-interaction --no-dev # run selenium - name: Run selenium run: poetry run python sample.py
ワークフローを実行してみる
workflow_dispatch
イベントトリガーを設定しているので,手動でワークフローを実行します.
Actionsのタブからrun_selenium
ワークフローを選択し,Run workflow
を押します.
するとワークフローが実行され,問題なくSeleniumが動かせていることが確認できました.
まとめ
今回はSeleniumを実行するGitHub Actionsのワークフローを作成してみました.
これを用いることで定期的にサイトの更新情報を取得したりできるので,どんどん活用していきたいと思います.
参考
- setup-chromedriver · Actions · GitHub Marketplace
- いまさらだけどGithub actions上でseleniumを動かしたのでまとめてみた - Qiita
リンク