-
-
Save fabtho/13e4a2e7cfbfde671b8fa81bbe9359fb to your computer and use it in GitHub Desktop.
#!/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') |
@trojblue unfortunately, the code still does not work as intended (atleast for me).
I tried to make a screenshot of this -> https://stackoverflow.com/questions/41721734/take-screenshot-of-full-page-with-selenium-python-with-chromedriver but the problem is that it cuts a portion of the end of a page.
I am currently trying to fix it, if I manage to fix it, I will provide the fix. (But it would be awesome if someone more competent tried to fix it)
P.S - if you take a close look, you can see on the image a few pixels comming from that black footer, which indicates there should be another text in between the footer and the page (footer is cropped as well)
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. 😢
fixed imports & added a line to remove persistent element such as navbar when scrolling: