Overview
This article explains how to use the Selenium library in Python to programmatically launch major browsers such as Google Chrome, Microsoft Edge, Firefox, and Safari. We will also cover the correct way to use the termination method (quit) to ensure no background processes remain, and distinguish it from the method used to close only a specific tab (close).
Specifications
- Input: None (script execution only).
- Output:
- Launches a window of the specified web browser.
- Closes the browser upon process completion.
- Requirements:
- The
seleniumlibrary must be installed. - The target web browser must be installed on the PC.
- The
Basic Usage
This is the standard code to launch Google Chrome and close it after 3 seconds.
from selenium import webdriver
import time
# Launch Chrome browser
driver = webdriver.Chrome()
# Wait for 3 seconds to confirm launch
time.sleep(3)
# Completely terminate the browser (Mandatory)
driver.quit()
Full Code Example
This example uses a try...finally block to ensure the browser closes even if an error occurs. It includes startup code for the four major browsers (unused ones are commented out).
from selenium import webdriver
import time
def launch_browser_safely():
"""
Demo function to launch and safely terminate a browser.
"""
driver = None
try:
print("Launching the browser...")
# --- Browser Selection (Uncomment the one you need) ---
# 1. Google Chrome
driver = webdriver.Chrome()
# 2. Microsoft Edge
# driver = webdriver.Edge()
# 3. Mozilla Firefox
# driver = webdriver.Firefox()
# 4. Apple Safari (macOS only)
# driver = webdriver.Safari()
print(f"Successfully launched: {driver.name}")
# Perform actions (e.g., Open Google)
driver.get("https://www.google.com")
time.sleep(3) # Wait for confirmation
except Exception as e:
print(f"An error occurred: {e}")
finally:
# Always close the browser regardless of errors
if driver:
print("Closing the browser.")
driver.quit()
if __name__ == "__main__":
launch_browser_safely()
Customization Points
Terminology for Closing Browsers
Selenium provides two methods for closing browsers. Generally, you should use quit().
| Method | Action | Purpose |
| driver.quit() | Full Termination | Closes all windows and tabs and destroys the WebDriver process. Call this at the end of the program. |
| driver.close() | Close Tab | Closes only the window or tab currently in focus. The process continues if other tabs are open. |
Browser Driver Classes
Choose the appropriate class from the webdriver module based on your browser:
webdriver.Chrome()webdriver.Edge()webdriver.Firefox()webdriver.Safari()
Important Notes
Ghost Processes
If you forget to call driver.quit() or if the script crashes before reaching it, browser and driver processes (like chromedriver.exe) will stay active in the background, consuming memory. Always use a try...finally block to ensure quit() is executed in the finally section.
Safari Setup
To control Safari on macOS, you must enable “Allow Remote Automation” under the “Develop” menu in Safari’s menu bar.
Initial Load Wait
Browsers can be slow immediately after startup. Attempting to interact (like clicking) immediately may result in a failure. It is standard practice to include logic that waits for the page to finish loading.
Advanced Application
Using a Python context manager allows you to handle termination automatically without explicitly writing quit().
from selenium import webdriver
from contextlib import contextmanager
@contextmanager
def managed_chrome():
"""Context manager to handle Chrome driver startup and shutdown."""
driver = webdriver.Chrome()
try:
yield driver
finally:
driver.quit()
if __name__ == "__main__":
# quit() is automatically called after exiting the 'with' block
with managed_chrome() as driver:
driver.get("https://www.google.com")
print(driver.title)
