How to Fix a Transparent Background in a PhantomJS Screenshot (Python 3, Selenium)

You can use PhantomJS to take a screenshot of a web page from Python code.

If you take a screenshot and the background is transparent:

shows a screenshot with transparency problems

You can use this suggestion to set a default background color for the web page.

Using the above suggestion, and code from here (with some slight modifications):

from selenium import webdriver

driver = webdriver.PhantomJS(executable_path='/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs')
driver.set_window_size(1920, 1080)
driver.get("https://simpletutorials.com/")

driver.execute_script("""(function() {
    var style = document.createElement('style'), text = document.createTextNode('body { background: #fff }');
    style.setAttribute('type', 'text/css');
    style.appendChild(text);
    document.head.insertBefore(style, document.head.firstChild);
})();""")
driver.save_screenshot('screenshot.png')
driver.quit()

I was able to take a screenshot with white as the default background:

shows a screenshot without transparency problems

Comments

Leave a comment

What color are green eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.