Controlling the browser window size helps test how a website looks and works on different screen sizes.
0
0
Window size control in Selenium Python
Introduction
Testing if a website layout adjusts correctly on small or large screens.
Checking if buttons and text are visible without scrolling.
Simulating mobile or tablet screen sizes on a desktop browser.
Ensuring pop-ups or dialogs fit inside the window.
Verifying responsive design behavior during automated tests.
Syntax
Selenium Python
driver.set_window_size(width, height)
# width and height are integers representing pixelsUse driver.set_window_size() to set the browser window size.
Width is the horizontal size, height is the vertical size in pixels.
Examples
Sets the browser window to 1024 pixels wide and 768 pixels tall.
Selenium Python
driver.set_window_size(1024, 768)
Simulates an iPhone 8 screen size for testing mobile layout.
Selenium Python
driver.set_window_size(375, 667)
Sample Program
This script opens a browser, navigates to example.com, sets the window size to 800x600 pixels, then prints the current window size.
Selenium Python
from selenium import webdriver # Start the browser with webdriver.Chrome() as driver: # Open a website driver.get('https://example.com') # Set window size to 800x600 driver.set_window_size(800, 600) # Get current window size size = driver.get_window_size() print(f"Width: {size['width']}, Height: {size['height']}")
OutputSuccess
Important Notes
Always set window size before interacting with page elements to avoid layout issues.
Use driver.get_window_size() to confirm the current window size.
Remember some browsers may have minimum window sizes; setting smaller sizes might not work as expected.
Summary
Window size control helps test responsive design by simulating different screen sizes.
Use set_window_size(width, height) to change the browser window size.
Check the window size with get_window_size() to verify changes.