Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Close Specific Web Pages Using Selenium in Python
Python's Selenium library provides powerful web automation capabilities, including the ability to manage multiple browser windows and tabs programmatically. In this tutorial, we'll explore how to close specific web pages using Selenium in Python, which is particularly useful when dealing with multiple browser instances during automated testing or web scraping tasks.
Setting Up Selenium in Python
Before we can close specific web pages, we need to set up our Selenium environment properly.
Installing Selenium
Install Selenium using pip with the following command:
pip install selenium
Installing ChromeDriver
Selenium requires a web driver to interact with browsers. For Chrome, download ChromeDriver from the official site and place it in your system PATH, or use the modern approach with WebDriverManager:
pip install webdriver-manager
Basic Setup
Here's how to set up a basic Selenium environment:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
# Setup Chrome driver with automatic driver management
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
print("Selenium WebDriver initialized successfully")
Selenium WebDriver initialized successfully
Opening Multiple Web Pages
Before closing specific pages, let's open multiple web pages to work with:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time
# Setup driver
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
# Open first page
driver.get("https://www.example.com")
print(f"Opened first page: {driver.title}")
# Open second page in new tab
driver.execute_script("window.open('https://www.google.com', '_blank');")
# Switch to the new tab and print title
driver.switch_to.window(driver.window_handles[1])
print(f"Opened second page: {driver.title}")
# Show all window handles
print(f"Total windows open: {len(driver.window_handles)}")
# Clean up
driver.quit()
Opened first page: Example Domain Opened second page: Google Total windows open: 2
Method 1: Closing Current Window
The simplest method is to close the currently active window using the close() method:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
# Open multiple pages
driver.get("https://www.example.com")
driver.execute_script("window.open('https://www.google.com', '_blank');")
print(f"Windows before closing: {len(driver.window_handles)}")
# Close current window
driver.close()
print(f"Windows after closing: {len(driver.window_handles)}")
# Switch to remaining window to continue or quit
if driver.window_handles:
driver.switch_to.window(driver.window_handles[0])
print(f"Switched to: {driver.title}")
driver.quit()
Windows before closing: 2 Windows after closing: 1 Switched to: Example Domain
Method 2: Closing Specific Window by Index
You can close a specific window by switching to it first, then closing it:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
# Open multiple pages
driver.get("https://www.example.com")
driver.execute_script("window.open('https://www.google.com', '_blank');")
driver.execute_script("window.open('https://www.github.com', '_blank');")
print(f"Total windows: {len(driver.window_handles)}")
# Close the second window (index 1)
target_window = driver.window_handles[1]
driver.switch_to.window(target_window)
print(f"Closing window: {driver.title}")
driver.close()
# Switch back to first window
driver.switch_to.window(driver.window_handles[0])
print(f"Remaining windows: {len(driver.window_handles)}")
print(f"Current window: {driver.title}")
driver.quit()
Total windows: 3 Closing window: Google Remaining windows: 2 Current window: Example Domain
Method 3: Closing Window by Title
This method searches for a window with a specific title and closes it:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
def close_window_by_title(driver, target_title):
"""Close a window with the specified title"""
current_window = driver.current_window_handle
for handle in driver.window_handles:
driver.switch_to.window(handle)
if target_title in driver.title:
print(f"Found and closing: {driver.title}")
driver.close()
break
# Switch back to original window if it still exists
if current_window in driver.window_handles:
driver.switch_to.window(current_window)
elif driver.window_handles:
driver.switch_to.window(driver.window_handles[0])
# Setup
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
# Open pages
driver.get("https://www.example.com")
driver.execute_script("window.open('https://www.google.com', '_blank');")
print(f"Windows before: {len(driver.window_handles)}")
# Close window with "Google" in title
close_window_by_title(driver, "Google")
print(f"Windows after: {len(driver.window_handles)}")
print(f"Current window: {driver.title}")
driver.quit()
Windows before: 2 Found and closing: Google Windows after: 1 Current window: Example Domain
Best Practices
Here are some important considerations when closing specific web pages:
Always check if windows exist before switching to avoid errors
Use try-catch blocks to handle potential exceptions
Switch to a valid window after closing one to continue automation
Use driver.quit() to close all windows and end the session
Safe Window Closing Function
def safe_close_window(driver, window_handle):
"""Safely close a specific window by handle"""
try:
if window_handle in driver.window_handles:
driver.switch_to.window(window_handle)
print(f"Closing: {driver.title}")
driver.close()
# Switch to first available window
if driver.window_handles:
driver.switch_to.window(driver.window_handles[0])
print(f"Switched to: {driver.title}")
return True
else:
print("Window handle not found")
return False
except Exception as e:
print(f"Error closing window: {e}")
return False
# Example usage
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.get("https://www.example.com")
driver.execute_script("window.open('https://www.google.com', '_blank');")
# Close the second window safely
second_window = driver.window_handles[1]
safe_close_window(driver, second_window)
driver.quit()
Closing: Google Switched to: Example Domain
Conclusion
Closing specific web pages in Selenium requires understanding window handles and proper switching between windows. Use driver.close() for individual windows and driver.quit() to end the entire session. Always implement error handling and ensure you switch to a valid window after closing one to maintain automation flow.
