Python: Selenium with PhantomJs to capture Screenshots

PhantomJS is
a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.

And

Selenium is
A portable software-testing framework for web applications. Selenium provides a record/playback tool for authoring tests without the need to learn a test scripting language (Selenium IDE)

Using the combination of selenium and PhantomJs can give you a way to capture screenshots and use it in your choices.

For that let's install PhantomJs in your computer.
For Ubuntu/Debian platform, you can use like this:

>sudo apt-get install phantomjs
        -------- OR --------
>sudo apt-get update
>sudo apt-get install build-essential chrpath libssl-dev libxft-dev
>sudo apt-get install libfreetype6 libfreetype6-dev
>sudo apt-get install libfontconfig1 libfontconfig1-dev
>cd ~
>wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2
>sudo tar xvjf phantomjs-2.1.1-linux-x86_64.tar.bz2
>sudo mv phantomjs-2.1.1-linux-x86_64 /usr/local/share
>sudo ln -sf /usr/local/share/phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/bin

Or use npm:

>npm install phantomjs2

Install selenium by using pip install selenium

Let's go to coding:

from selenium import webdriver  # Import selenium web driver

driver = webdriver.PhantomJs()  # PhantomJs webdriver

driver.get('https://google.com')

driver.save_screenshot('google.png')  

Done! your image will be saved as google.png.

Suppose you want to store the image in Django ImageFile, you can use the following code:

screenshot = driver.screenshot_as_base64()  # binary image

my_model = MyModel()  
my_model.image_field = ContentFile(screenshot, 'google.png')  
MyModel.save()  

That's all for now.
Cheers!!

comments powered by Disqus