Skip to content

Instantly share code, notes, and snippets.

@jsok
Created March 12, 2014 06:42
Use PhantomJS and Python Selenium bindings to take screenshots of websites.
import StringIO
from selenium import webdriver
from PIL import Image
# Install instructions
#
# npm install phantomjs
# sudo apt-get install libjpeg-dev
# pip install selenium pillow
driver = webdriver.PhantomJS(executable_path="node_modules/phantomjs/bin/phantomjs")
driver.set_window_size(1366, 728) # optional
driver.get('http://google.com')
driver.save_screenshot('screen_hires.png')
screen = driver.get_screenshot_as_png()
# Crop it back to the window size (it may be taller)
box = (0, 0, 1366, 728)
im = Image.open(StringIO.StringIO(screen))
region = im.crop(box)
region.save('screen_lores.jpg', 'JPEG', optimize=True, quality=95)
@Ryuno-Ki
Copy link

executable_path needs to be set to "node_modules/phantomjs/lib/phantom/bin/phantomjs" in recent versions of phantomjs.

In case you pass --save to npm install you'll get a record in your package.json, so it gets pinned (and shipped).

@shivamMg
Copy link

shivamMg commented Feb 2, 2017

for anyone using python3, you'll need to use from io import BytesIO instead of import StringIO, and im = Image.open(BytesIO(screen)) on line 22. Also I used Pillow 4.0.0 and save method on Image objects don't seem to have optimize and quality options anymore, so line 24 can just be region.save('screen_lores.jpg', 'JPEG')

@Debanjan-B
Copy link

@shivamMg Thanks a ton. Your comment helped a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment