Bird
Raised Fist0
Selenium Pythontesting~20 mins

Screenshot on failure in Selenium Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Screenshot Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output when the test fails and screenshot is taken?
Consider the following Selenium Python test snippet that tries to find a non-existing element and takes a screenshot on failure. What will be the output or result of running this code?
Selenium Python
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

try:
    driver = webdriver.Chrome()
    driver.get('https://example.com')
    driver.find_element('id', 'nonexistent')
except NoSuchElementException:
    driver.save_screenshot('failure.png')
    print('Screenshot saved on failure')
finally:
    driver.quit()
ARaises TimeoutException
BScreenshot saved on failure
CNo output, test passes silently
DSyntaxError due to wrong method call
Attempts:
2 left
💡 Hint
Look at the exception caught and what happens inside the except block.
❓ assertion
intermediate
1:30remaining
Which assertion correctly verifies screenshot file creation after failure?
After a test failure and screenshot capture, which assertion correctly checks that the screenshot file 'failure.png' exists?
Selenium Python
import os

# Assume screenshot is saved as 'failure.png' in current directory

# Which assertion below is correct?
Aassert os.path.isfile('failure.png')
Bassert os.path.exists('failure.png') == False
Cassert os.path.isdir('failure.png')
Dassert os.path.isfile('failure.png') == False
Attempts:
2 left
💡 Hint
Check which function verifies a file exists.
🔧 Debug
advanced
2:30remaining
Why does this screenshot code fail to save the image?
This Selenium Python code is supposed to save a screenshot on failure but does not create any file. What is the likely cause?
Selenium Python
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

try:
    driver = webdriver.Chrome()
    driver.get('https://example.com')
    driver.find_element('id', 'nonexistent')
except NoSuchElementException:
    driver.save_screenshot()
    print('Screenshot saved')
finally:
    driver.quit()
Asave_screenshot requires a filename argument, missing here
BNoSuchElementException is not caught properly
Cdriver.quit() is called before save_screenshot
Ddriver.get() URL is invalid
Attempts:
2 left
💡 Hint
Check the method call for saving screenshots.
❓ framework
advanced
3:00remaining
How to integrate screenshot on failure in pytest with Selenium?
Which pytest fixture code snippet correctly captures a screenshot on test failure using Selenium WebDriver?
A
import pytest

def pytest_runtest_setup(item):
    driver.save_screenshot('failure.png')
B
import pytest

@pytest.fixture(autouse=True)
def screenshot_on_failure(request, driver):
    yield
    if request.node.rep_call.failed:
        driver.save_screenshot('failure.png')
C
import pytest

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    if rep.when == 'call' and rep.failed:
        driver = item.funcargs['driver']
        driver.save_screenshot('failure.png')
D
import pytest

@pytest.fixture
def driver():
    driver = webdriver.Chrome()
    yield driver
    driver.save_screenshot('failure.png')
    driver.quit()
Attempts:
2 left
💡 Hint
Look for pytest hook that runs after test call and can access test result.
🧠 Conceptual
expert
1:30remaining
Why is taking screenshots on failure important in automated UI testing?
Select the best reason why automated UI tests should capture screenshots when they fail.
AScreenshots replace the need for logs and error messages
BScreenshots reduce test execution time significantly
CScreenshots prevent tests from failing by fixing bugs automatically
DScreenshots provide visual evidence of the UI state at failure, aiding debugging
Attempts:
2 left
💡 Hint
Think about how visual context helps when tests fail.

Practice

(1/5)
1. What is the main purpose of taking a screenshot on test failure in Selenium?
easy
A. To capture the current state of the web page for debugging
B. To speed up the test execution
C. To improve the browser's performance
D. To automatically fix the test errors

Solution

  1. Step 1: Understand the role of screenshots in testing

    Screenshots help testers see what the user saw when the test failed.
  2. Step 2: Identify the purpose of capturing screenshots on failure

    They provide visual evidence to debug UI problems quickly.
  3. Final Answer:

    To capture the current state of the web page for debugging -> Option A
  4. Quick Check:

    Screenshot on failure = capture page state [OK]
Hint: Screenshots show what failed looks like visually [OK]
Common Mistakes:
  • Thinking screenshots speed up tests
  • Believing screenshots fix errors automatically
  • Confusing screenshots with performance tools
2. Which of the following is the correct syntax to take a screenshot in Selenium Python when a test fails?
easy
A. driver.save_screenshot('error.png')
B. driver.takeScreenshot('error.png')
C. driver.capture('error.png')
D. driver.screenshotSave('error.png')

Solution

  1. Step 1: Recall Selenium Python screenshot method

    The correct method to save a screenshot is save_screenshot().
  2. Step 2: Verify method names and syntax

    Only driver.save_screenshot('error.png') matches Selenium's API.
  3. Final Answer:

    driver.save_screenshot('error.png') -> Option A
  4. Quick Check:

    Correct method name = save_screenshot [OK]
Hint: Remember method is save_screenshot with underscore [OK]
Common Mistakes:
  • Using camelCase instead of snake_case
  • Using non-existent methods like capture or screenshotSave
  • Missing parentheses or quotes
3. What will be the output if the following Selenium Python code runs and the element is not found?
try:
    driver.find_element(By.ID, 'submit').click()
except Exception as e:
    driver.save_screenshot('fail.png')
    print('Screenshot saved on failure')
medium
A. No output, test passes silently
B. RuntimeError without screenshot
C. SyntaxError due to missing import
D. Screenshot saved on failure

Solution

  1. Step 1: Analyze try-except behavior on element not found

    If element is missing, exception triggers except block.
  2. Step 2: Check actions in except block

    Screenshot is saved and message printed: 'Screenshot saved on failure'.
  3. Final Answer:

    Screenshot saved on failure -> Option D
  4. Quick Check:

    Exception triggers screenshot and print [OK]
Hint: Exception triggers except block actions [OK]
Common Mistakes:
  • Assuming test passes silently on failure
  • Confusing syntax errors with runtime exceptions
  • Ignoring the print statement inside except
4. Identify the error in this Selenium Python snippet intended to save a screenshot on failure:
try:
    driver.find_element(By.NAME, 'login').click()
except:
    driver.save_screenshot(failure.png)
medium
A. No error, code is correct
B. Incorrect exception handling syntax
C. Missing quotes around filename in save_screenshot
D. Wrong method name saveScreenshot instead of save_screenshot

Solution

  1. Step 1: Check save_screenshot argument syntax

    Filename must be a string in quotes, but here it is unquoted.
  2. Step 2: Confirm exception handling and method name

    Except syntax and method name are correct; only filename is wrong.
  3. Final Answer:

    Missing quotes around filename in save_screenshot -> Option C
  4. Quick Check:

    Filename must be a string in quotes [OK]
Hint: Always put filename in quotes for save_screenshot [OK]
Common Mistakes:
  • Forgetting quotes around filename string
  • Changing method name incorrectly
  • Misusing except syntax
5. You want to automatically take a screenshot only when a Selenium test fails and save it with a timestamp. Which approach below correctly implements this in Python?
hard
A. Use driver.save_screenshot('fail.png') outside try-except block
B. Use try-except around test steps, call driver.save_screenshot(f"fail_{time.time()}.png") in except
C. Call driver.save_screenshot() before every test step unconditionally
D. Use a loop to retry test steps and save screenshot on success

Solution

  1. Step 1: Understand when to take screenshots

    Screenshots should be taken only on failure, inside except block.
  2. Step 2: Use timestamp for unique filenames

    Using time.time() in filename ensures unique screenshot names.
  3. Final Answer:

    Use try-except around test steps, call driver.save_screenshot(f"fail_{time.time()}.png") in except -> Option B
  4. Quick Check:

    Screenshot on failure with timestamp = try-except + formatted filename [OK]
Hint: Take screenshots only in except block with timestamped names [OK]
Common Mistakes:
  • Taking screenshots before test steps always
  • Saving screenshots outside exception handling
  • Retrying tests without capturing failure screenshots
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard