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 では動作しました。
 
 -