LoginSignup
9
6

More than 1 year has passed since last update.

【Chrome】Seleniumでページ全体のスクリーンショットを撮る

Last updated at Posted at 2021-05-20

Chrome DevTools Protocolというものがあることを知り、Seleniumからも利用できるようなので、試してみました。

せっかくなのでページ全体のスクリーンショットを取得してみます。
ページ全体のスクリーンショットは、こちらの記事で紹介されている方法で取得できますが、これをChrome DevTools Protocolを使って実現してみます。

cdp_screenshot.py
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import base64

def take_full_screenshot(driver, file_path):
    width = driver.execute_script("return document.body.scrollWidth;")
    height = driver.execute_script("return document.body.scrollHeight;")
    viewport = {
        "x": 0, 
        "y": 0,
        "width": width,
        "height": height,
        "scale": 1
    }
    # Chrome Devtools Protocolコマンドを実行し、取得できるBase64形式の画像データをデコードしてファイルに保存
    image_base64 = driver.execute_cdp_cmd("Page.captureScreenshot", {"clip": viewport, "captureBeyondViewport": True})
    image = base64.b64decode(image_base64["data"])
    with open(file_path, 'bw') as f:
        f.write(image)

# Webdriver ManagerでChromeDriverを取得
driver = webdriver.Chrome(ChromeDriverManager().install())

driver.get('https://qiita.com/')
take_full_screenshot(driver, 'screenshot.png')

driver.close()
driver.quit()
  • Page.captureScreenshotを使うことでスクリーンショットが撮れるようです。
  • clipパラメータにページ全体のサイズを渡しただけでは、見えている範囲のみしか取得できなかったため、captureBeyondViewportというパラメータをTrueに設定しました。
    • captureBeyondViewportは、実験的なパラメータのようなので、今後利用できなくなる可能性はあります。
    • とりあえず、手元のMacのChrome 90.0.4430 では動作しました。

参考

9
6
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
9
6