DEV Community

loading...

Selenium 4 and chrome driver, take full page screenshots

gdledsan profile image Mundo Updated on ・1 min read

I spent some time playing with Selenium 4 trying to get a full page screenshot, this is what I found.

  1. We will use the devtools protocol of Chrome Driver
  2. this is done by driver.execute_cdp_cmd(command, parameters)
  3. The command is Page.captureScreenshot
  4. Parameters are documented here
  5. the tricky param is clip
# I am assuming we already have a driver object.

# We need the dimensions of the content
page_rect = driver.execute_cdp_cmd('Page.getLayoutMetrics', {})

# parameters needed for ful page screenshot
# note we are setting the width and height of the viewport to screenshot, same as the site's content size
screenshot_config = {'captureBeyondViewport': True,
                             'fromSurface': True,
                             'clip': {'width': page_rect['contentSize']['width'],
                                      'height': page_rect['contentSize']['height'],
                                      'x': 0,
                                      'y': 0,
                                      'scale': 1},
                             }
# Dictionary with 1 key: data
base_64_png = driver.execute_cdp_cmd('Page.captureScreenshot', screenshot_config)

# Write img to file
with open("imageToSave.png", "wb") as fh:
    fh.write(base64.urlsafe_b64decode(base_64_png['data'))

Enter fullscreen mode Exit fullscreen mode

Why am I writing this?

There is no good documentation related to the DevTools protocol and its integration to selenium is still in the works in Selenium 4 at the time I wrote this.

I Hope this helps any lost soul.

Discussion (0)

pic
Editor guide