Skip to content
CodeKruPro

Save a Screenshot of the Viewport

68/80

Save a Screenshot of the Viewport

save_screenshot writes the current viewport to a file under /workspace. It is not a full-page capture. Print whether the call returned true and whether the file size is greater than 0.

Task:

  1. Open Buttons
  2. Save /workspace/viewport.png
  3. Print both checks

Print the lines below exactly.

Expected output:

Screenshot taken: True
File has content: True

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

  1. Choose a path inside the workspace folder, ending in .png.
  2. Call save_screenshot with it and keep what it returns.
  3. Turn the returned value into text with str() before joining it to its label.
  4. 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 False and no traceback. The size check then fails with FileNotFoundError.

  • Joining a bool to text

    The return value and the size comparison are both bool. Adding either to a label raises TypeError.

  • 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.

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.

main.py
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()