pythonselenium-webdriver

Creating a screenshot of the full screen using selenium in headless mode?


I try to create a screenshot of the full screen in selenium headless-mode using the following code:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import time

options = Options()
options.add_argument('--headless=new')
options.add_argument('--window-size=1920x1080')
srv=Service()

driver = webdriver.Chrome (service=srv, options=options)

driver.get ("https://www.orf.at/")
time.sleep(2)

driver.save_screenshot("screen.png")  

But the created screenshot is only the very upper left part of the screen:

enter image description here

And this is how the site looks like on my 1920x1080 screen:

enter image description here

How can i get the full screenshot using selenium in headless mode?


Solution

  • from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    # Configure Chrome options
    options = Options()
    options.add_argument("--headless")  # Use headless mode
    
    driver = webdriver.Chrome(options=options)
    
    driver.get("https://spicejet.com")
    
    # Adjust the window size to the full page height
    total_height = driver.execute_script("return document.body.scrollHeight")
    driver.set_window_size(1920, total_height)
    
    # Take the screenshot
    driver.save_screenshot("fullpage.png")
    
    driver.quit()