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

Selenium脚本执行完成后Google Chrome浏览器自动关闭问题咨询

解决脚本执行后Chrome自动关闭的问题

你的脚本执行完毕后浏览器自动关闭,是因为Selenium 4及以上版本的默认行为——当驱动实例的生命周期随脚本结束而终止时,浏览器会自动退出。以下是两种可行的解决方法:

方法1:配置Chrome保持打开状态

通过ChromeOptions添加detach实验性选项,让浏览器在脚本执行完成后继续保持运行。修改后的完整代码如下:

import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

# 配置Chrome选项,禁用自动关闭
options = Options()
options.add_experimental_option("detach", True)

sev_obj = Service("C:\\Drivers\\chromedriver-win64\\chromedriver.exe")
# 传入配置好的options和service对象初始化驱动
driver = webdriver.Chrome(service=sev_obj, options=options)

driver.get("https://www.google.com/")
driver.maximize_window()

driver.find_element(By.NAME, "q").send_keys("Selenium")
driver.find_element(By.NAME, "q").submit()

time.sleep(5)
driver.find_element(By.XPATH, "//a[@href='https://www.selenium.dev/']//h3[@class='LC20lb MBeuO DKV0Md'][normalize-space()='Selenium']").click()

方法2:添加阻塞代码延迟脚本结束

在脚本的最后一行添加输入阻塞语句,让脚本不会立即结束,直到用户手动触发:

# 在脚本末尾添加这一行
input("按任意键关闭浏览器...")

这样浏览器会保持打开状态,直到你按下任意键,脚本才会结束并关闭浏览器。

另外注意:你原代码中定义了sev_obj但未传入webdriver.Chrome(),虽然不影响运行,但建议像方法1中那样加上service=sev_obj,保持代码规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 08:46:24