import os
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# Setup Chrome options for headless mode (optional)
chrome_options = Options()
chrome_options.add_argument('--headless=new')
chrome_options.add_argument('--window-size=1920,1080')
# Setup Chrome driver service
service = Service()
driver = webdriver.Chrome(service=service, options=chrome_options)
try:
# Navigate to the webpage
driver.get('https://example.com')
# Wait until the body element is present to ensure page load
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'body')))
# Pause briefly to allow any dynamic content to load
time.sleep(1)
# Take full page screenshot (works in Chrome 59+)
screenshot_path = 'full_page_screenshot.png'
driver.get_full_page_screenshot_as_file(screenshot_path)
# Assertions
assert os.path.exists(screenshot_path), f"Screenshot file {screenshot_path} does not exist"
assert os.path.getsize(screenshot_path) > 0, "Screenshot file is empty"
finally:
driver.quit()This script uses Selenium WebDriver with Chrome in headless mode to open the webpage https://example.com. It waits explicitly for the <body> tag to be present, ensuring the page is loaded. Then it pauses briefly to allow dynamic content to settle.
The key method get_full_page_screenshot_as_file() captures the entire page, not just the visible viewport. The screenshot is saved as full_page_screenshot.png.
After taking the screenshot, the script asserts that the file exists and is not empty, confirming the screenshot was successfully saved.
Finally, the browser is closed properly in the finally block to avoid resource leaks.