Skip to content

Instantly share code, notes, and snippets.

@memakura
Last active Oct 14, 2018
Embed
What would you like to do?
Full-page screenshot for Selenium
# -*- coding: utf-8 -*-
# Original:
# https://gist.github.com/yui3880/a63ced61806d8517c4a3
# https://qiita.com/myhr/items/dff7cee30182ab56f737
#
# Changelog:
# - Use in-memory process
# - Remove fullsize flag
# - Replace self to driver
# - Add scrollbar removal
# - etc.
#
# Usage:
# 1. For Windows, set "Scale and layout" to 100% in Display Settings
# 2. Coding
# from selenium import webdriver
# import fullscreenshot as fss
# driver = webdriver.Chrome()
# driver.get(<URL>)
# fss.save_fullscreenshot(driver, 'screenshot-full.png')
# driver.quit()
from PIL import Image
import io
def save_fullscreenshot(driver, filename):
""" Capture a full-page screenshot using image stitching """
orig_overflow = driver.execute_script("return document.body.style.overflow;")
driver.execute_script("document.body.style.overflow = 'hidden';") # scrollbar
total_height = driver.execute_script("return document.body.scrollHeight;")
total_width = driver.execute_script("return document.body.scrollWidth;")
view_width = driver.execute_script("return window.innerWidth;")
view_height = driver.execute_script("return window.innerHeight;")
stitched_image = Image.new("RGB", (total_width, total_height))
scroll_height = 0
while scroll_height < total_height:
col_count = 0
scroll_width = 0
driver.execute_script("window.scrollTo(%d, %d)" % (scroll_width, scroll_height))
while scroll_width < total_width:
if col_count > 0:
driver.execute_script("window.scrollBy("+str(view_width)+",0)")
img = Image.open(io.BytesIO(driver.get_screenshot_as_png()))
if scroll_width + view_width >= total_width \
or scroll_height + view_height >= total_height: # need cropping
new_width = view_width
new_height = view_height
if scroll_width + view_width >= total_width:
new_width = total_width - scroll_width
if scroll_height + view_height >= total_height:
new_height = total_height - scroll_height
stitched_image.paste(
img.crop((view_width - new_width, view_height - new_height,
view_width, view_height)),
(scroll_width, scroll_height)
)
scroll_width += new_width
else: # no cropping
stitched_image.paste(img, (scroll_width, scroll_height))
scroll_width += view_width
col_count += 1
scroll_height += view_height
driver.execute_script("document.body.style.overflow = '" + orig_overflow + "';")
stitched_image.save(filename)
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment