LoginSignup
0
2

More than 1 year has passed since last update.

Seleniumで実行中の画面を録画する

Last updated at Posted at 2022-05-02

はじめに

Seleniumでテストを実行した時などに、テストエビデンスやテストが失敗した原因を探すために有用となる、実行時の画面を録画する方法について書きます。
SeleniumのDockerイメージのGitHubページに説明されている方法を利用します。

selenium-video.gif

環境

  • Python 3.6.8
  • CentOS 7.9

準備: Seleniumインストール

前提として、DockerとPythonは利用できる環境とします。
pythonのseleniumパッケージをインストールします。

$ pip3 install selenium --user

手元の環境では、pip3 install seleniumと実行すると、PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.6'というエラーになったため、以下の記事を参考にして、--userオプションを付与してインストールしました。

実行

SeleniumのDokerイメージのGitHubページにあるドキュメントの説明に従って、以下のように実行します。

$ docker network create grid
$ docker run -d -p 4444:4444 -p 6900:5900 --net grid --name selenium --shm-size="2g" selenium/standalone-chrome:4.1.4-20220427
$ docker run -d --net grid --name video -e FILE_NAME=chrome_video.mp4 -v /tmp/videos:/videos selenium/video:ffmpeg-4.3.1-20220427
$ python3 selenium-record-video.py
$ docker stop video && docker rm video
$ docker stop selenium && docker rm selenium
$ docker network rm grid
  • -e FILE_NAME=chrome_video.mp4の環境変数の指定で、動画ファイルの名前を指定します。
  • 上記を実行すると、/tmp/videosに動画ファイルが生成されます。
  • 生成されたMP4ファイルをアニメーションGIFに変換したものが「はじめに」の画像です(動画の前後をカットしています)。

テストコード

上記の手順中で利用したテストコードです。

selenium-record-video.py
from selenium import webdriver
import os
import time

# Chromeのオプション
options = webdriver.ChromeOptions()
options.add_argument("--start-maximized")

with webdriver.Remote(
            command_executor='http://localhost:4444/wd/hub',
            options=options) as driver:
    # Qiitaにアクセス
    driver.get('https://qiita.com/')
    assert driver.title == "Qiita"
    # スクリーンショットを取得し保存
    filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),
            "screenshot_qiita.png")
    driver.save_screenshot(filename)

    # 検索窓に「Selenium」と入力し、検索
    search_box = driver.find_element_by_name("q")
    search_box.send_keys('Selenium')
    search_box.submit()

    # 検索結果の1件目にアクセス
    driver.find_element_by_xpath('//h1[@class="searchResult_itemTitle"]').click()
    time.sleep(3)
    # スクリーンショットを取得し保存
    filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),
            "screenshot_article.png")
    driver.save_screenshot(filename)

  • Qiitaトップページにアクセスし、「Selenium」と検索して、検索結果の1件目にアクセスします。
  • Qiitaのトップページと検索結果の1件目のサイトのスクリーンショットを保存します。

参考

本記事の作成にあたり、以下を参考にさせていただきました。

0
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
0
2