Maximize and minimize window in Selenium Python - Build an Automation Script
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options import time # Setup Chrome options options = Options() options.add_argument('--disable-infobars') # Setup WebDriver service service = Service() driver = webdriver.Chrome(service=service, options=options) try: # Open browser driver.get('https://www.example.com') # Maximize window driver.maximize_window() time.sleep(1) # Wait a moment for the window to maximize # Verify maximize by checking window size is close to screen size window_size = driver.get_window_size() screen_width = driver.execute_script('return screen.width') screen_height = driver.execute_script('return screen.height') assert window_size['width'] >= screen_width * 0.9, f"Window width {window_size['width']} is less than 90% of screen width {screen_width}" assert window_size['height'] >= screen_height * 0.9, f"Window height {window_size['height']} is less than 90% of screen height {screen_height}" # Minimize window driver.minimize_window() time.sleep(1) # Wait a moment for the window to minimize # Verify minimize by checking window is not visible or size is very small # Selenium does not provide direct API to check minimized state, # so we check window size is very small or zero minimized_size = driver.get_window_size() assert minimized_size['width'] < 100, f"Window width {minimized_size['width']} is not small after minimize" assert minimized_size['height'] < 100, f"Window height {minimized_size['height']} is not small after minimize" finally: # Close browser driver.quit()
This script uses Selenium WebDriver with Python to automate maximizing and minimizing the browser window.
First, it opens the browser and navigates to a website.
Then it maximizes the window using driver.maximize_window() and verifies the window size is close to the screen size by comparing widths and heights.
Next, it minimizes the window using driver.minimize_window(). Since Selenium does not provide a direct way to check if the window is minimized, it verifies by checking the window size is very small.
Finally, it closes the browser in a finally block to ensure cleanup even if assertions fail.
Short time.sleep() calls are used to allow the window state to update before verification.
Now add data-driven testing with 3 different URLs to open before maximizing and minimizing