Introduction
In this article, we will discuss how to close recently opened Chrome windows using Python. This can be helpful when you want to automate the process of closing multiple Chrome windows, for instance, when you are working on a Python project and need to open and close several Chrome windows for testing or data collection.
Prerequisites
To follow along with this article, you will need:
- Python 3 installed on your system
- Selenium WebDriver installed for Python
- Google Chrome browser installed on your system
Setting Up Selenium WebDriver
First, you need to install and set up Selenium WebDriver for Python. You can install it using pip:
pip install selenium
After installing Selenium, you need to download the ChromeDriver executable from the ChromeDriver downloads page. Extract the downloaded archive and note the location of the ChromeDriver executable.
Writing the Python Script
Now, let's write the Python script to close all recently opened Chrome windows. Here's the code:
import time
from selenium import webdriver
def close_all_windows():
Initialize the Chrome driver
driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
Get all the window handles
handles = driver.window_handles
Close all the windows except the first one
for handle in handles:
if handle != handles[0]:
driver.switch_to.window(handle)
driver.close()
Switch back to the first window
driver.switch_to.window(handles[0])
Close the driver
driver.quit()
Replace "/path/to/chromedriver" with the actual path to the ChromeDriver executable on your system.
Running the Python Script
To run the script, save it to a file with a .py extension, for instance, "close_chrome_windows.py". Then, open a terminal or command prompt, navigate to the directory containing the script, and run:
python close_chrome_windows.py
The script will close all the recently opened Chrome windows, except the first one.
In this article, we learned how to close all recently opened Chrome windows using Python and Selenium WebDriver. This can be useful when you need to automate the process of closing multiple Chrome windows for testing or data collection.