Last active
December 12, 2022 08:07
-
-
Save fabtho/13e4a2e7cfbfde671b8fa81bbe9359fb to your computer and use it in GitHub Desktop.
make full screenshot with selenium in python
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
#!/usr/bin/python | |
from selenium import webdriver | |
from PIL import Image | |
from cStringIO import StringIO | |
verbose = 1 | |
browser = webdriver.Firefox() | |
browser.get('http://stackoverflow.com/questions/37906704/taking-a-whole-page-screenshot-with-selenium-marionette-in-python') | |
# from here http://stackoverflow.com/questions/1145850/how-to-get-height-of-entire-document-with-javascript | |
js = 'return Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);' | |
scrollheight = browser.execute_script(js) | |
if verbose > 0: | |
print scrollheight | |
slices = [] | |
offset = 0 | |
while offset < scrollheight: | |
if verbose > 0: | |
print offset | |
browser.execute_script("window.scrollTo(0, %s);" % offset) | |
img = Image.open(StringIO(browser.get_screenshot_as_png())) | |
offset += img.size[1] | |
slices.append(img) | |
if verbose > 0: | |
browser.get_screenshot_as_file('%s/screen_%s.png' % ('/tmp', offset)) | |
print scrollheight | |
screenshot = Image.new('RGB', (slices[0].size[0], offset)) | |
offset = 0 | |
for img in slices: | |
screenshot.paste(img, (0, offset)) | |
offset += img.size[1] | |
screenshot.save('/tmp/test.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For anyone else who ends up here: in Selenium 4+ there's a
save_full_page_screenshot()
function for this that only works with Firefox. Give it a try, but don't expect miracles. In my case the page rendered strangely. 😢