MacOS下Python+Selenium实现关闭浏览器时自动终止ChromeDriver进程
如何在关闭Chrome窗口时自动终止ChromeDriver进程(MacOS + Selenium场景)
问题场景
在MacOS系统上使用Python的Selenium编写工作代码,功能为解析文本文件中的字符串,打开Chrome浏览器窗口,为每个字符串新建标签页并搜索仅显示昨日及以后的结果。代码功能正常,但手动关闭浏览器窗口/标签页后,ChromeDriver进程仍会在程序坞中运行,希望实现类似正常浏览器的行为——关闭窗口时自动终止进程。
使用版本信息
- Python: 3.11.1
- Selenium: 4.7.2
- MacOS: Monterey 12.4
- Chrome: 108.0.5359.124
- 最新版Chromedriver
原代码
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import WebDriverException from selenium.common.exceptions import InvalidSessionIdException from contextlib import suppress from datetime import date from datetime import timedelta import sys import urllib3 from selenium.common.exceptions import NoSuchWindowException import time chrome_options = Options() chrome_options.add_experimental_option("detach", True) driver = webdriver.Chrome(options=chrome_options) today = date.today() print(today) yesterday = today - timedelta(days = 1) yesterdaystr = yesterday.strftime('%Y-%m-%d') print(yesterdaystr) file = open("testdoc.txt", "r") filelist = file.readlines() for i in range(len(filelist)): driver.get("https://www.google.com/search?q=" + filelist[i] + " after:" + yesterdaystr + "&start=") if i < (len(filelist) - 1): driver.switch_to.new_window('tab')
尝试过的无效方案
曾尝试通过监听driver.window_handles判断窗口是否关闭,进而执行driver.quit(),但循环仅能短暂运行,仅极少数场景生效:
while True: if len(driver.window_handles) == 0: driver.quit() break
问题根源与解决方法
1. 核心问题:detach=True选项
你添加的chrome_options.add_experimental_option("detach", True)是导致ChromeDriver进程残留的直接原因——这个选项的设计目的就是让ChromeDriver在浏览器关闭后继续独立运行,必须移除该选项。
2. 监听循环失效的原因
当手动关闭浏览器后,Selenium的会话已直接失效,此时调用driver.window_handles会立即抛出InvalidSessionIdException或WebDriverException,导致循环直接终止,无法执行后续的driver.quit()逻辑。
3. 正确实现方式
移除detach选项,并通过异常捕获监听会话状态,一旦检测到会话失效(即浏览器已关闭),就执行清理操作:
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import InvalidSessionIdException, WebDriverException from datetime import date, timedelta import time from contextlib import suppress # 移除detach选项,恢复默认的进程绑定行为 chrome_options = Options() driver = webdriver.Chrome(options=chrome_options) today = date.today() yesterday = today - timedelta(days=1) yesterdaystr = yesterday.strftime('%Y-%m-%d') # 使用with语句安全处理文件,自动关闭 with open("testdoc.txt", "r") as file: filelist = [line.strip() for line in file.readlines() if line.strip()] for i, query in enumerate(filelist): # 构造搜索URL,避免字符串拼接的冗余 search_url = f"https://www.google.com/search?q={query} after:{yesterdaystr}&start=" driver.get(search_url) if i < len(filelist) - 1: driver.switch_to.new_window('tab') # 监听浏览器会话状态 while True: try: # 尝试获取当前窗口句柄,验证会话是否有效 driver.current_window_handle time.sleep(1) # 降低循环频率,减少CPU占用 except (InvalidSessionIdException, WebDriverException): # 会话失效,说明浏览器已被关闭 with suppress(WebDriverException): driver.quit() break
关键优化点说明
- 移除
detach=True:让ChromeDriver与浏览器进程绑定,默认情况下关闭浏览器后进程会自动退出,这是基础。 - 异常捕获逻辑:通过尝试执行
driver.current_window_handle验证会话状态,捕获会话失效的异常后执行driver.quit(),确保进程被彻底清理。 time.sleep(1):避免循环高频运行占用过多CPU资源。- 文件处理优化:用
with语句自动关闭文件,同时过滤空行,避免无效搜索。
内容的提问来源于stack exchange,提问作者erduley
相关产品推荐
相关产品推荐

