Python爬虫使用Chrome时如何在正常退出时同时关闭Chrome.exe进程?
用 selenuim+chrome 来实现爬虫,爬完后 chrome.exe 进程会驻留,在程序末尾无论是用 driver.close()还是 driver.quit()都无法退出 chrome.exe 进程,请问代码要如何才能在爬完后杀掉 chrome.exe 进程呢?谢谢
Python爬虫使用Chrome时如何在正常退出时同时关闭Chrome.exe进程?
3 回复
import atexit
import os
import signal
import subprocess
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
class ChromeDriverWithCleanup:
def __init__(self, chrome_driver_path='chromedriver.exe', chrome_path=None):
self.chrome_driver_path = chrome_driver_path
self.chrome_path = chrome_path
self.driver = None
self.chrome_process = None
def start(self):
"""启动Chrome并设置退出清理"""
chrome_options = Options()
# 禁用GPU加速和沙箱,减少进程残留
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--no-sandbox')
# 使用远程调试端口,方便后续关闭
chrome_options.add_argument('--remote-debugging-port=9222')
# 如果指定了Chrome路径
if self.chrome_path:
chrome_options.binary_location = self.chrome_path
# 创建服务
service = Service(executable_path=self.chrome_driver_path)
# 启动浏览器
self.driver = webdriver.Chrome(service=service, options=chrome_options)
# 获取Chrome进程ID(Windows)
if os.name == 'nt':
self._get_chrome_process_windows()
# 注册退出清理函数
atexit.register(self.cleanup)
return self.driver
def _get_chrome_process_windows(self):
"""Windows系统获取Chrome进程信息"""
try:
import psutil
current_pid = os.getpid()
# 查找Chrome进程
for proc in psutil.process_iter(['pid', 'name', 'ppid']):
try:
if 'chrome' in proc.info['name'].lower() and proc.info['ppid'] == current_pid:
self.chrome_process = proc
break
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
except ImportError:
print("建议安装psutil库以更精确管理进程: pip install psutil")
def cleanup(self):
"""清理函数,关闭浏览器和进程"""
if self.driver:
try:
# 1. 先尝试正常关闭driver
self.driver.quit()
except Exception as e:
print(f"正常关闭driver时出错: {e}")
# 2. 强制终止进程(Windows)
if os.name == 'nt' and self.chrome_process:
try:
os.kill(self.chrome_process.pid, signal.SIGTERM)
except Exception as e:
print(f"终止进程时出错: {e}")
# 3. 通用清理命令
self._kill_chrome_processes()
# 4. 确保driver引用被清除
self.driver = None
def _kill_chrome_processes(self):
"""通用方法终止Chrome进程"""
try:
if os.name == 'nt': # Windows
os.system('taskkill /f /im chrome.exe >nul 2>&1')
else: # Linux/Mac
os.system('pkill -f chrome >/dev/null 2>&1')
except Exception as e:
print(f"清理Chrome进程时出错: {e}")
def __enter__(self):
"""上下文管理器入口"""
return self.start()
def __exit__(self, exc_type, exc_val, exc_tb):
"""上下文管理器退出"""
self.cleanup()
# 使用示例
if __name__ == "__main__":
# 方法1:使用上下文管理器(推荐)
with ChromeDriverWithCleanup() as driver:
driver.get("https://www.example.com")
print("页面标题:", driver.title)
# 执行爬虫操作...
time.sleep(2)
# 退出with块时自动清理
# 方法2:手动管理
chrome_manager = ChromeDriverWithCleanup(
chrome_driver_path='chromedriver.exe',
chrome_path=r'C:\Program Files\Google\Chrome\Application\chrome.exe'
)
driver = chrome_manager.start()
try:
driver.get("https://www.example.com")
# 执行爬虫操作...
finally:
chrome_manager.cleanup()
核心方案:使用atexit注册退出钩子,结合driver.quit()和进程强制终止。
总结建议:用上下文管理器确保浏览器进程总被清理。
close 只是关闭打开的 tab,直接 quit 就能退出的,如不过不能退出说明不是 webdriver 关联的,你想强行杀掉直接调用系统相应的进程关闭处理就行了,windows 下的 taskkill、linux/mac 下的 killall
有些 chrome 的进程是 它的后台进程, 你不用管那么多, quit 就行了

