Selenium Can Make Hi-DPI, Retina Style Screenshots (Firefox and Chrome)

With just a single line of code you can modify your Selenium browser to operate in (x.x) density mode. This means you can take higher-DPI screenshots as you might on retina screens.


Firefox Code Sample

my_dpi = 2.0

profile = webdriver.FirefoxProfile()
profile.set_preference("layout.css.devPixelsPerPx", str(my_dpi))

Yes kids, it is this simple. All you need to do is set a preference on your profile.

NOTE: The gotcha here is that you have to cast the float to a string using str(). That is non-obvious and will save you a ton of time in debugging. Otherwise it is silently ignored.


Chrome Code Sample

Chrome is a little different. There is not a preferences profile that you tweak with various settings. In this case you simple pass in a command line option when launching the browser.

my_dpi = 2.0
options = ChromeOptions()
    # ... other options..
    options.add_argument(f"--force-device-scale-factor={my_dpi}")

Full Code Sample

This is an export from my Jupyter Notebook. Note, you will need to pip install selenium as well as have the firefox-geckodriver installed with brew or whatever linux flavor.

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.common.exceptions import NoSuchElementException, WebDriverException
from time import sleep

my_dpi = 2.0

profile = webdriver.FirefoxProfile()
profile.set_preference("layout.css.devPixelsPerPx", str(my_dpi))

options = Options()
options.headless = True
driver = webdriver.Firefox(options=options, firefox_profile=profile)
driver.set_page_load_timeout(60)
driver.set_window_size(1440, 800)

driver.get('https://www.simplecto.com')

driver.save_screenshot("simplecto-dpi2.0.png")
driver.quit()

NOTE: This was not tested on Windows. Sorry not sorry.

You can try DPI at 1.0 and 2.0 to see the sizable difference in disk space and memory required. This becomes a little more work for a CPU when running full-size page screenshots.

Show Comments