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

Selenium执行后Chrome标签页自动关闭:如何保持标签页开启?

解决Selenium Chrome执行后自动关闭的问题

你的代码执行完成后浏览器立即关闭,是因为Python脚本运行结束时,driver对象被销毁,触发了浏览器的关闭动作。以下两种方法可以让浏览器保持开启状态:

方法1:添加手动等待

在脚本末尾添加输入等待,让程序暂停执行,直到你手动输入内容后才结束,这样浏览器就会一直保持打开:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

driver_service=Service(executable_path=r'./chromedriver.exe')
driver = webdriver.Chrome(service=driver_service)

driver.get('https://google.com')
driver.find_element(By.NAME, 'q').send_keys('word'+Keys.RETURN)

# 添加这行,等待用户输入后才结束程序
input("按任意键关闭浏览器...")

方法2:启用Chrome的detach模式

通过ChromeOptions添加detach实验性选项,让浏览器在脚本执行完毕后继续运行,不需要手动干预:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

# 配置Chrome选项
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)

driver_service=Service(executable_path=r'./chromedriver.exe')
# 初始化driver时传入options参数
driver = webdriver.Chrome(service=driver_service, options=chrome_options)

driver.get('https://google.com')
driver.find_element(By.NAME, 'q').send_keys('word'+Keys.RETURN)

注意:你的原代码缺少By和Keys的导入,上面的示例已经补充了这部分,否则运行时会报错。

内容的提问来源于stack exchange,提问作者Abdo Rahal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:25:20