Selenium控制Chrome浏览器自动关闭问题求助
Selenium Chrome浏览器自动关闭问题的原因及解决办法
常见原因
- ChromeDriver与Chrome浏览器版本不兼容:两者版本必须严格匹配,版本差异过大时,驱动会触发异常,导致浏览器进程直接退出。
- 脚本执行完毕后driver实例被自动回收:Python脚本运行到最后一行时,垃圾回收机制会销毁driver对象,关联的浏览器进程也会随之关闭。
- 页面跳转或元素操作触发未捕获的异常:比如登录后页面加载超时、元素定位失败,脚本报错退出,浏览器也会跟着关闭。
对应解决办法
- 修复版本兼容问题
先查看Chrome浏览器版本(右上角菜单→帮助→关于Google Chrome),下载同大版本的ChromeDriver。初始化driver时指定驱动路径:
from selenium.webdriver.chrome.service import Service # 替换为你的ChromeDriver实际路径 service = Service(r"C:\path\to\chromedriver.exe") options = webdriver.ChromeOptions() options.binary_location = r"C:\Program Files\Google\Chrome\Application\chrome.exe" driver = webdriver.Chrome(service=service, options=options)
注:新版Selenium不再支持executable_path参数,需用Service类配置驱动路径。
- 阻止脚本执行完毕后回收driver
在脚本末尾添加阻塞代码,让脚本保持运行状态,避免driver被回收:
# 登录判断逻辑后添加 input("按回车键关闭浏览器...") driver.quit()
或者添加detach实验性选项,强制浏览器在脚本结束后保持打开:
options.add_experimental_option("detach", True)
- 处理页面跳转异常
登录后不要直接判断current_url,添加显式等待确保页面加载完成,避免因页面未加载完成导致脚本提前结束:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 点击登录按钮后 try: # 等待10秒,直到目标URL加载完成 WebDriverWait(driver, 10).until(EC.url_to_be("https://www.example.com/index.phtml")) print("登录成功!") except: print("登录失败或页面加载超时")
内容的提问来源于stack exchange,提问作者Ellmi
相关产品推荐
相关产品推荐

