How to Close Browser in Selenium: Syntax and Examples
In Selenium, you can close the current browser window using
driver.close() or close all browser windows and end the session using driver.quit(). Use close() to close one window and quit() to exit the entire browser session.Syntax
driver.close(): Closes the current browser window that the driver is controlling.
driver.quit(): Closes all browser windows opened by the driver and ends the WebDriver session.
python
driver.close() driver.quit()
Example
This example opens a browser, navigates to a website, then closes the current window with close() and finally quits the browser session with quit().
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') # Run browser in headless mode service = Service() driver = webdriver.Chrome(service=service, options=options) driver.get('https://example.com') print('Title:', driver.title) driver.close() # Closes current window # After close(), the driver session still exists if multiple windows were open # To fully end session, use quit() driver.quit()
Output
Title: Example Domain
Common Pitfalls
- Using
driver.close()when multiple windows are open closes only the current window, leaving others open. - Not calling
driver.quit()at the end can leave browser processes running in the background. - Calling
driver.quit()before finishing tests will cause errors because the session ends immediately.
python
from selenium import webdriver # Wrong: quitting too early # driver.quit() # driver.get('https://example.com') # This will cause error because session ended # Right: driver = webdriver.Chrome() driver.get('https://example.com') driver.quit() # Ends session after test
Quick Reference
| Method | Description |
|---|---|
| driver.close() | Closes the current browser window |
| driver.quit() | Closes all browser windows and ends the WebDriver session |
Key Takeaways
Use driver.close() to close the current browser window only.
Use driver.quit() to close all windows and end the WebDriver session.
Always call driver.quit() at the end to avoid leftover browser processes.
Do not call driver.quit() before your test actions are complete.
driver.close() does not end the WebDriver session if multiple windows are open.