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

Python Selenium无driver.quit时脚本执行完浏览器自动关闭如何解决

问题原因

你定义的driver是MAC()方法内的局部变量,当方法执行完毕、整个脚本运行结束后,这个局部变量会被Python的垃圾回收机制自动销毁,绑定的ChromeDriver进程随之退出,就会自动关闭浏览器,和你写不写driver.quit()没有关系。

解决方案

你可以任选以下任意一种方式解决:

  • 方案1:给Chrome启动配置添加detach参数,强制浏览器在驱动进程退出后保持打开
    只需要在你初始化ChromeOptions的代码段添加一行配置即可:
    options=webdriver.ChromeOptions()
    # 新增这一行
    options.add_experimental_option("detach", True)
    
  • 方案2:把driver设置为类属性/全局变量,避免方法执行完就被回收
    修改后的参考代码如下:
    import selenium
    import time
    import random
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    options=webdriver.ChromeOptions()
    PATH="C:\Coding_projects\chromedriver.exe"
    class AppleWebsite():
        # 定义类属性存储driver
        driver = None
        def MAC():
            AppleWebsite.driver=webdriver.Chrome(PATH,options=options)
            AppleWebsite.driver.get("https://www.apple.com/fr/iphone-12/")
            MAC=AppleWebsite.driver.find_element_by_xpath('//*[@id="ac-globalnav"]/div/ul[2]/li[3]/a')
            MAC.click()
            time.sleep(random.randint(2,9))
            MAC_AIR=AppleWebsite.driver.find_element_by_xpath('//*[@id="chapternav"]/div/ul/li[2]/a')
            MAC_AIR.click()
    AppleWebsite.MAC()
    
  • 方案3:在方法末尾添加阻塞语句,让脚本不直接运行结束
    比如在MAC()方法最后加一行input("按回车后退出浏览器"),脚本会等待你在终端输入内容再退出,期间driver不会被销毁,浏览器就会保持打开。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:48:03