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

5.3k Views Asked by At

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?

2

There are 2 best solutions below

2
On BEST ANSWER

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

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

With the code below, you can set window size. *My answer explains it more:

chrome_options.add_argument('--window-size=1024,768')

Or:

driver.set_window_size(1024, 768)