Seleniumは2004 年にThoughtWorks社によって開発された、Webブラウザの操作を自動化するためのフレームワークです。
Webブラウザの操作の自動化や、Web サイトのクローリングなどの用途で利用されています。
この記事ではPythonでSeleniumを利用して、ブラウザ(Google chrome)上で特定のWebページのスクリーンショットを自動で取得する方法及びサンプルソースコードを紹介します。
Seleniumの環境構築や開発前の準備については以下の記事にまとめています。
Webページのスクリーンショットを自動取得するソースコード
今回は開発環境として以下を用いました。
- Windows 10
- Python 3.9
- Selenium 4.0.0
- Google chrome102.0.5005.63
早速、ソースコードを見ていきましょう。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from selenium import webdriver
# Open web-driver
webDriver = webdriver.Chrome('chromedriver102.exe')
# Access to URL
webDriver.get('http://tecsingularity.com/')
# Set image(window) size
webDriver.set_window_size(1920, 1080)
# Save screenshot
webDriver.save_screenshot('screenshot.png')
# Close web-driver
webDriver.quit();
解説
特定のページへのアクセス
特定のWebページにアクセスするのは以下の箇所です。今回はこのホームページのトップ(http://tecsingularity.com/)にアクセスする形としていますが、用途に応じて変更してください。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
webDriver.get('http://tecsingularity.com/')
ブラウザのスクリーンサイズの変更
次に、ブラウザのウインドウの解像度を設定します。近年だと1920×1080の画面を使われている方が多いと思いますので、今回は1920×1080に設定しました。
このコマンドにより、特定のページにアクセスした後、Google chromeのウィンドウのサイズが1920×1080に変更されます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
webDriver.set_window_size(1920, 1080)
スクリーンショットの取得
最後に以下の箇所でスクリーンショットを取得します。
スクリーンショットは、カレントディレクトリ(基本的には実行したpyファイルが存在するフォルダ)に出力されます。
スクリーンショットは、ブラウザのウィンドウ上に見えている部分のみが取得されます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
webDriver.save_screenshot('screenshot.png')
出力結果
実行すると、以下のように当サイトのトップページのスクリーンショットが自動保存されました。

まとめ
今回はSeleniumとPythonを用いて、特定のページのスクリーンショットを取得する方法を紹介しました。