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

Selenium WebDriver启动Chrome后页面立即关闭问题求解

解决Chrome浏览器启动后迅速关闭的问题

原因分析

  • 脚本执行完毕后,Python进程退出,WebDriver实例被销毁,导致浏览器自动关闭。
  • 第二个示例代码中显式调用了driver.close(),会主动关闭当前浏览器窗口。

具体解决方法

方法1:添加阻塞代码,防止脚本立即结束

在代码末尾添加输入等待,让脚本保持运行状态,浏览器就不会随进程退出而关闭:

from selenium import webdriver as opcoesSelenium

navegador = opcoesSelenium.Chrome()
navegador.get("https://rpachallengeocr.azurewebsites.net/")

# 等待用户输入后再结束脚本,保持浏览器打开
input("Press Enter to close the browser...")
navegador.quit()

方法2:移除主动关闭语句并添加阻塞(针对第二个示例)

删掉代码里的driver.close(),同时添加阻塞逻辑:

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

driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
driver.get("http://www.python.org")

# 去掉driver.close(),添加阻塞
input("Press Enter to exit...")
driver.quit()

方法3:配置Chrome参数实现浏览器持久化(可选)

通过ChromeOptions添加参数,让浏览器在WebDriver实例销毁后仍保持打开状态:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager

chrome_options = Options()
# 添加参数,使浏览器在驱动结束后不自动关闭
chrome_options.add_experimental_option("detach", True)

driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options=chrome_options)
driver.get("http://www.python.org")

注意:使用该参数后,脚本结束时浏览器会保持打开,需手动关闭;若需自动化关闭,仍建议结合input阻塞后调用driver.quit()。

内容的提问来源于stack exchange,提问作者Alain dos Santos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 22:58:24