Skip to content
CodeKruPro

Quit the browser with a with statement

Automation taskEasy-MediumPython onlyAsked in: Accenture, TCS, Wipro

Interviewers ask: "How do you make sure the browser always closes, even when the test fails?" In Python, a with block quits the driver for you when the block ends, even after an error (the driver works as a context manager, an object that cleans up when the block ends). A finally block, or a pytest fixture (a setup and clean-up function) that quits after yield, does the same job.

Quit the Browser with a Context Manager

Quit the Browser with a Context Manager

with webdriver.Chrome() as driver quits the browser when the block ends, including when a line raises an error. Use this after finally is already a habit.

Task:

  1. Open Chrome with a with statement
  2. Open Text Fields
  3. Print the title

Print the lines below exactly.

Expected output:

Title: Text Fields