About this lesson
Save a viewport screenshot with save_screenshot in Selenium Python
Selenium Python AssignmentsAdvancedScreenshots
How it works
driver.save_screenshot(path) writes what the browser currently shows as a PNG file. It returns a bool: True when the file was written, False when not. It raises nothing on failure. A folder that did not exist and a folder I could not write to both just returned False.
"Viewport" is the key word. The headless window reported 780 by 580, but the saved image was 780 by 437 pixels, since the page area is smaller than the window. The Buttons page scrolls to 1016 pixels, so the image holds only the visible part.
End the path with .png. Without it, Python prints a UserWarning, though the file is still written. To confirm the file, os.path.getsize returns bytes and raises FileNotFoundError for a missing file. get_screenshot_as_png and get_screenshot_as_base64 give bytes and str instead of a file.
About the assignment
You capture the Buttons page into the workspace folder, then print two checks: whether the call said it worked and whether the file holds data.
What you will do
- Choose a path inside the workspace folder, ending in
.png. - Call
save_screenshotwith it and keep what it returns. - Turn the returned value into text with
str()before joining it to its label. - Get the file size with
os.path.getsize, compare it with zero, and print the second line from that.
Common mistakes
Ignoring a False return
A path in a missing folder gives
Falseand no traceback. The size check then fails withFileNotFoundError.Joining a bool to text
The return value and the size comparison are both
bool. Adding either to a label raisesTypeError.Expecting the whole page
Content below the fold is not in the image, so scroll first.
In a real test suite
Suites capture a screenshot when a test fails. In pytest that is usually a fixture or hook that saves a file named after the test, so a CI run keeps proof of each failure.
The next lesson narrows the same idea to a single element.
Related lessons
- Save a Screenshot of One ElementCapture one element instead of the whole viewport.
- Set the Window SizeThe window size affects how much a screenshot can show.
- Open Chrome and Read the Page TitleThe first script, which opens a page and quits the browser the same way.
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
import os
driver = webdriver.Chrome()
try:
driver.get("https://testkru.com/Elements/Buttons")
# Save /workspace/viewport.png and print both lines
finally:
driver.quit()