You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium启动Chrome浏览器后自动退出问题求助

Selenium Chrome浏览器自动退出问题解决方法

你的代码核心问题是:定义了启用detach特性的ChromeOptions,但初始化webdriver.Chrome实例时没有传入这个配置,导致detach未生效,脚本执行完毕后浏览器自动关闭。

修正后的代码

直接将配置好的options传入Chrome构造函数即可:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
s = Service(ChromeDriverManager().install())
# 关键:传入options参数
driver = webdriver.Chrome(service=s, options=options)
driver.get("https://amazon.com")

其他可选解决方案

  1. 添加阻塞代码
    如果不想依赖detach选项,可以在脚本末尾添加阻塞逻辑,让脚本持续运行直到用户触发关闭操作:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

s = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=s)
driver.get("https://amazon.com")
# 脚本会停在这里,直到用户按下回车
input("按回车键关闭浏览器...")
# 释放资源(可选,手动关闭浏览器后也会自动释放)
driver.quit()
  1. 检查版本兼容性
    确保Chrome浏览器与ChromeDriver版本完全匹配,webdriver-manager通常会自动适配,但如果遇到异常,可以手动指定驱动版本:
# 示例:指定ChromeDriver版本为114.0.5735.90(需与你的Chrome版本对应)
s = Service(ChromeDriverManager(driver_version="114.0.5735.90").install())

内容的提问来源于stack exchange,提问作者Vadim Nave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 20:10:26