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

Python-Selenium执行后浏览器标签页自动关闭问题求助

Python Selenium浏览器自动关闭问题的解决办法

问题根源

Python代码执行完毕后,解释器会自动回收driver对象,连带终止浏览器进程,这和Java的资源回收逻辑不同,所以出现了和Java版Selenium不一样的表现。

可行解决方案

  • 添加阻塞语句:在页面加载完成后加入等待代码,阻止程序立即结束

    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    import time
    
    ser_obj = Service("D:\\Python\\chromedriver-win64\\chromedriver.exe")
    driver = webdriver.Chrome(service=ser_obj)
    driver.get("https://gmail.com")
    time.sleep(10)  # 浏览器保持10秒后关闭
    # 也可以用input等待用户手动触发结束
    # input("按回车键关闭浏览器...")
    
  • 用detach配置项(推荐):给Chrome添加实验性配置,让脚本结束后浏览器保持打开

    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    from selenium.webdriver.chrome.options import Options
    
    chrome_options = Options()
    chrome_options.add_experimental_option("detach", True)
    
    ser_obj = Service("D:\\Python\\chromedriver-win64\\chromedriver.exe")
    driver = webdriver.Chrome(service=ser_obj, options=chrome_options)
    driver.get("https://gmail.com")
    
  • 结合with语句与交互等待:用with管理资源,同时通过用户输入阻止进程结束

    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    
    ser_obj = Service("D:\\Python\\chromedriver-win64\\chromedriver.exe")
    with webdriver.Chrome(service=ser_obj) as driver:
        driver.get("https://gmail.com")
        input("操作完成后按回车键关闭浏览器...")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 01:52:07