January 6, 2016
When given a website and an image on that website, the task is to take a screen capture of that image on the page it appears on the site.
Manually: enter the website, find the given image (scroll if needed), take the screenshot and save it to the disk.
But what can you do when you have thousands of screenshots to take per hour?
You can employ hundreds of people to handle this scale, but…
This is kind of expensive and what should you do if your scale increases or decreases?
Automate it: if only we could write a piece of software that could do exactly what we need…
So what do we actually need? Something that can:
1) Imitate a browser
2) Find an image on a webpage
3) Take the screenshot
Let me introduce PhantomJS:
Headless refers to the fact that the program can be run from the command line without a window system.
Web Kit is the open-source web browsing engine that powers popular browsers like Chrome.
How to use it?
There are many ways to use PhantomJS, here at PicScout we use Selenium Web Driver to run PhantomJS. Selenium can control PhantomJS in the same way that it does any other browser.
How does it help me to take a screen capture?
After receiving the location we can use PhantomJS to take a screen capture, despite the fact that PhantomJS is a Headless browser it still can render a web page as well as a web driver.
Running several instances of PhantomJS – problems and solutions
Problem #1: zombie processes. In our app we create and kill PhantomJS processes, we have noticed that after some time there are many zombie instances of PhantomJS.
Solution #1: for unknown reasons, occasionally we are unable to create a new PhantomJS instance. This happen when an exception is thrown and a new PhantomJS process starts. Now we need to manually find the process id and kill it.
Problem #2: low success rate on high CPU usage – when CPU reached 100% we were receiving a lot of errors from PhantomJS.
Solution #2: number of PhantomJS instances should be set according to ‘computing power’. Notice that most of the time PhantomJS won’t consume much CPU but there are websites for which this isn’t the case, you should take this into consideration when you decide how many PhantomJS processes you would like to run.
Problem #3: sometimes the screen capture fails without any apparent reason.
Solution #3: we were able to increase the screen capture success rate by using a retry mechanism.