使用Selenium爬虫时Chrome WebDriver自动关闭的问题求助
Chrome WebDriver启动后自动关闭的解决方案
你的代码中添加了detach: True但仍出现自动关闭,最可能的原因是驱动对象的作用域问题:ch_driver是函数内的局部变量,当launchBrowser()函数执行完毕后,局部变量被Python垃圾回收机制回收,导致浏览器进程随之关闭。
以下是针对性的修复方案:
方案1:将驱动对象声明为全局变量
通过global关键字让驱动对象在函数外也能被引用,避免函数执行完后被回收:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager def launchBrowser(): global ch_driver ch_options = webdriver.ChromeOptions() ch_options.add_experimental_option("detach", True) ch_options.add_experimental_option('excludeSwitches', ['enable-logging']) ch_driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=ch_options) ch_driver.get("你的目标URL") # 替换为实际要访问的url launchBrowser()
方案2:函数返回驱动对象,外部持有引用
让函数返回驱动实例,在函数外部保存这个引用,维持驱动对象的生命周期:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager def launchBrowser(): ch_options = webdriver.ChromeOptions() ch_options.add_experimental_option("detach", True) ch_options.add_experimental_option('excludeSwitches', ['enable-logging']) ch_driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=ch_options) ch_driver.get("你的目标URL") return ch_driver # 外部持有驱动引用,避免被回收 driver = launchBrowser()
额外排查点
如果上述方案仍无效,检查以下内容:
- 确认Chrome浏览器与ChromeDriver版本完全匹配:即使使用ChromeDriverManager,偶尔也会出现版本同步延迟,手动核对两者主版本号(比如Chrome是118.x,ChromeDriver也必须是118.x)。
- 关闭Chrome自动更新:自动更新可能导致版本不匹配,可通过组策略或修改注册表禁用更新。
- 排查杀毒软件/防火墙:部分安全软件会拦截WebDriver的进程,尝试临时关闭后测试。
内容的提问来源于stack exchange,提问作者Dreikh
相关产品推荐
相关产品推荐

