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

Python中使用Selenium时如何保持Chrome浏览器不自动关闭?

问题:Selenium打开Chrome窗口后自动快速关闭

我在Visual Studio编辑器中通过Python代码调用Selenium打开谷歌页面,使用的代码如下:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

#browser = webdriver.Chrome(ChromeDriverManager().install())
Path = "C:\\Program Files (x86)\\chromedriver.exe"
browser = webdriver.Chrome(Path)
browser.get('https://www.google.com/')

但运行后打开的Chrome窗口仅停留2-3秒就自动关闭了,求解决办法。


解决办法

  • 暂停脚本执行:Python脚本执行完所有代码后会自动销毁webdriver实例,导致Chrome窗口关闭。可以在代码末尾添加暂停逻辑,让脚本等待用户操作或一段时间后再结束:

    from selenium import webdriver
    from webdriver_manager.chrome import ChromeDriverManager
    
    Path = "C:\\Program Files (x86)\\chromedriver.exe"
    browser = webdriver.Chrome(Path)
    browser.get('https://www.google.com/')
    input("按任意键关闭窗口...")  # 脚本会等待输入才结束运行
    

    或者用time.sleep()设定固定停留时长:

    import time
    from selenium import webdriver
    from webdriver_manager.chrome import ChromeDriverManager
    
    Path = "C:\\Program Files (x86)\\chromedriver.exe"
    browser = webdriver.Chrome(Path)
    browser.get('https://www.google.com/')
    time.sleep(10)  # 窗口会保持10秒后关闭
    
  • 配置Chrome保持窗口存活:通过ChromeOptions添加detach实验参数,让Chrome窗口在webdriver实例销毁后依然保持打开状态:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.add_experimental_option("detach", True)
    Path = "C:\\Program Files (x86)\\chromedriver.exe"
    browser = webdriver.Chrome(executable_path=Path, options=options)
    browser.get('https://www.google.com/')
    
  • 推荐使用webdriver-manager管理驱动:你注释掉的代码其实更省心,不需要手动指定驱动路径,还能自动匹配Chrome版本,结合detach参数的完整代码如下:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from webdriver_manager.chrome import ChromeDriverManager
    
    options = Options()
    options.add_experimental_option("detach", True)
    browser = webdriver.Chrome(ChromeDriverManager().install(), options=options)
    browser.get('https://www.google.com/')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:35:19