Search code examples
pythonselenium-webdriverselenium-chromedriverscreenshotwindow-size

How to take screenshot with the same window size in Selenium in Python?


I want to take a screenshot in headless mode using Selenium at specific resolution, but even if I set the driver window size, the screenshot is taken at a different resolution:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

width = 1024
height = 768

chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--headless')

driver = webdriver.Chrome(options=chrome_options)
driver.set_window_size(width, height)

driver.get('https://google.com')
print('Window size', driver.get_window_size())
# Window size {'width': 1024, 'height': 768}

driver.save_screenshot('screenshot.png')  # <--  Screenshot is saved at different resolution

How can I take a screenshot at the same resolution of driver window size (1024x768 in this example) without have to post-process the saved image?


Solution

  • There's the window-size option you could add.

    chrome_options.add_argument('window-size=1024x768')