Python Selenium启动的Chrome窗口自动关闭问题求助
问题分析与解决方案
你的代码本身没有语法问题,浏览器自动关闭的核心原因是:当Python脚本执行完毕后,Selenium会自动销毁WebDriver实例,导致关联的浏览器窗口被关闭。其他设备上窗口不关闭,大概率是因为运行环境的Selenium版本较低(旧版本Selenium不会自动销毁实例),或者脚本执行后有其他阻塞逻辑。
以下是几种可行的解决方法:
方法一:添加阻塞代码
在脚本末尾加入输入等待,让脚本保持运行状态,浏览器就不会被关闭:from selenium import webdriver browser = webdriver.Chrome() browser.get("http://youtube.com") # 等待用户输入任意内容后才结束脚本 input("按下回车键关闭浏览器...")方法二:配置ChromeOptions启用detach模式
通过设置Chrome的启动参数,让浏览器在WebDriver实例销毁后依然保持打开:from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() # 启用detach参数,阻止浏览器自动关闭 chrome_options.add_experimental_option("detach", True) browser = webdriver.Chrome(options=chrome_options) browser.get("http://youtube.com")方法三:使用Selenium Service类(适用于Selenium 4+)
如果你使用的是Selenium 4及以上版本,也可以通过Service类来配置:from selenium import webdriver from selenium.webdriver.chrome.service import Service service = Service() # 设置保持浏览器打开 service.keep_alive = True browser = webdriver.Chrome(service=service) browser.get("http://youtube.com")
内容的提问来源于stack exchange,提问作者dragonmoney111
相关产品推荐
相关产品推荐

