0
0
Selenium Pythontesting~5 mins

Closing browser (close vs quit) in Selenium Python

Choose your learning style9 modes available
Introduction

We close the browser to end the test and free up computer resources. Knowing the difference between close() and quit() helps avoid errors and keeps tests clean.

When you want to close only the current browser tab after a test step.
When your test opens multiple tabs and you want to close them one by one.
When you want to end the whole browser session and close all tabs at once.
When cleaning up after a test to avoid leftover browser windows.
When you want to restart the browser fresh for a new test.
Syntax
Selenium Python
driver.close()
driver.quit()

driver.close() closes the current browser window or tab.

driver.quit() closes all browser windows and ends the WebDriver session.

Examples
This closes only the current tab or window your test is working on.
Selenium Python
driver.close()
This closes all tabs and windows opened by the WebDriver and ends the session.
Selenium Python
driver.quit()
Opens a page and then closes that single tab.
Selenium Python
driver.get('https://example.com')
driver.close()
Opens a page and then closes the entire browser session.
Selenium Python
driver.get('https://example.com')
driver.quit()
Sample Program

This script shows how close() closes only the current window, while quit() ends the whole browser session. After closing or quitting, trying to use the driver causes an error.

Selenium Python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--headless=new')  # Run browser in headless mode for testing
service = Service()
driver = webdriver.Chrome(service=service, options=options)

# Open a website
driver.get('https://example.com')
print('Title before close:', driver.title)

# Close current window
driver.close()

# Trying to get title after close will raise an error
try:
    print('Title after close:', driver.title)
except Exception as e:
    print('Error after close:', e)

# Start new driver session
driver = webdriver.Chrome(service=service, options=options)
driver.get('https://example.com')
print('Title before quit:', driver.title)

# Quit entire browser session
driver.quit()

# Trying to get title after quit will raise an error
try:
    print('Title after quit:', driver.title)
except Exception as e:
    print('Error after quit:', e)
OutputSuccess
Important Notes

Use close() when you have multiple tabs and want to close one.

Use quit() to clean up everything after your test finishes.

After calling close() or quit(), the WebDriver session may become invalid.

Summary

close() closes the current browser window or tab.

quit() closes all browser windows and ends the WebDriver session.

Use the right method to avoid errors and keep tests clean.