While working with Selenium and Chrome undetected drivers, I encountered an issue where the driver.quit() command was not terminating the Chrome sessions properly due to a bug. This resulted in lingering Chrome processes, which could lead to resource exhaustion and other issues.
To address this problem, I created a batch file named kill.bat with the following content to terminate the Chrome sessions forcibly:
set arg1=%1
taskkill /f /T /pid %arg1%
This batch file uses the taskkill command to forcefully and recursively terminate the process with the given process ID (PID).
Read Also: How to Become a Hacker: 14 Essential Tips for Beginners
Next, I modified my Selenium script to use this batch file for terminating the Chrome sessions. Here is the updated code snippet:
import os
from selenium import webdriver
from undetected_chromedriver.v2 import Chrome, ChromeOptions
# Initialize the Chrome undetected driver
options = ChromeOptions()
driver = Chrome(options=options)
# Perform your Selenium tasks here
# Get the browser process ID
browser_pid = driver.browser_pid
# Terminate the Chrome session using the batch file
os.system(r'kill.bat ' + str(browser_pid))
In this code:
- I import the necessary modules.
- Initialize the Chrome undetected driver with any required options.
- Perform the desired Selenium tasks.
- Retrieve the browser’s process ID (browser_pid).
- Use the os.system() method to execute the kill.bat file, passing the browser_pid as an argument.
This approach ensures that the Chrome sessions are terminated cleanly, avoiding any lingering processes and potential resource issues.

Leave a Comment