Python: Selenium with PhantomJs to capture ScreenshotsMar 21, 2017 · 2 Min Read · 2 Likes · 4 Comments
This article is deprecated as PhantomJs has been deprecated from Selenium as driver.
Using the combination of selenium and PhantomJs can give you a way to capture screenshots and use it in your choices.
Installation of PhantomJs
For that let’s install PhantomJs in your computer. For Ubuntu/Debian platform, you can use like this:
>sudo apt-get install phantomjs
>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
>npm install phantomjs2
Installation of Selenium
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.jpg')
Done! your image will be saved as google.jpg.
Using with Django
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.jpg') MyModel.save()
That’s all for now. Cheers!!
If you like this article, you can buy me a coffee. Thanks!
Last updated: Jun 02, 2023
Hi there! Great article, thanks very much for sharing. By any chance, is there a way of changing the language and region settings which can be seen in the resulting screenshots? Cheers, Thorben
If you can change the language and region settings from your browser, then you can simulate this using selenium, and then you can take the desired screenshot 😄
Currently I think we can’t use phantomjs in python. Because its support is cut off. Is it true?
Yes, it is no longer supported. The official documentation does not have mention of PhantomJS.