About this lesson
Selenium Python set_window_size and get_window_size: set a window to 1024 by 768
Selenium Python AssignmentsAdvancedWindow Management
How it works
A page can lay itself out differently at different widths, so tests often fix the window size first. driver.set_window_size(width, height) takes two integers. Passing one tuple fails with TypeError about a missing positional argument.
driver.get_window_size() returns a plain dictionary with the keys width and height, both integers. A dictionary has no dot access, so size.width raises AttributeError, and a misspelled key raises KeyError. Read values with square brackets. Adding an int to a string raises TypeError, so convert it first.
The numbers describe the outer window. The area where the page renders is smaller. After a window of 800 by 600, JavaScript reported an inner height of 457. For layout checks the inner area matters. Here, the dictionary you read back is the evidence.
Bad input is refused. A negative width raised InvalidArgumentException saying the width is out of range.
About the assignment
Resize the headless Chrome window, then read the size back from the driver instead of printing the numbers you typed.
What you will do
- Load the Buttons page.
- Set the window to 1024 wide and 768 tall.
- Store the dictionary the driver returns for the current size.
- Print two labelled lines, pulling width and height from that dictionary by key and converting each to text.
Common mistakes
Expecting attribute access on the result
The size is a
dict.size.widthraisesAttributeError: 'dict' object has no attribute 'width'. Use square brackets and the key.Concatenating a number
Adding the width to a label raises
TypeErrorwith the messagecan only concatenate str (not "int") to str. Wrap it instr()or use an f-string.Printing the values you set
Typing the numbers into the print line looks right but proves nothing. Read the size back from the browser.
In a real test suite
Suites set the window once, inside a driver fixture in conftest.py, so every test starts with the same dimensions. Responsive checks are often parametrized over a few widths.
Size can decide whether a test passes at all. Lesson 59 needs a larger window before a drag lands.
Related lessons
- Open a Tab and Return to the Original WindowAnother window setting: opening and closing tabs.
- Drag a Box onto a Drop ZoneNeeds a larger window, since the drop zone is out of view at the default size.
- Open Chrome and Read the Page TitleThe first lesson that reads a driver property and prints it.
To try one of these calls on any page without a task, open the Online Selenium Python Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
from selenium import webdriver
driver = webdriver.Chrome()
try:
driver.get("https://testkru.com/Elements/Buttons")
# Set 1024 by 768 and print the size you read back
finally:
driver.quit()