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

Selenium报错求助:无法保持Google页面显示问题如何解决

解决Selenium Chrome窗口自动关闭的问题

当Python脚本执行完毕时,driver对象会被垃圾回收,导致Chrome浏览器进程终止,窗口随之关闭。以下几种方法可以让窗口保持显示:

方法1:添加暂停指令

在代码末尾加入等待逻辑,阻止脚本立即结束:

  • 用input()等待用户操作:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

driver = webdriver.Chrome(service=Service(r"C:\Program Files (x86)\chromedriver.exe"))
driver.get('https://www.google.com/')
input("按回车键关闭窗口...")  # 程序暂停,直到用户按下回车才结束
  • 用time.sleep()设置固定延时:
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

driver = webdriver.Chrome(service=Service(r"C:\Program Files (x86)\chromedriver.exe"))
driver.get('https://www.google.com/')
time.sleep(30)  # 窗口会保持30秒后自动关闭

方法2:配置Chrome的detach参数

通过ChromeOptions添加detach实验选项,让浏览器在脚本结束后独立运行:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(
    service=Service(r"C:\Program Files (x86)\chromedriver.exe"),
    options=options
)
driver.get('https://www.google.com/')

这种方法无需手动干预,脚本执行完成后浏览器窗口会持续保留。

注意:Windows系统下的文件路径建议使用原始字符串r"路径"或双反斜杠\\,避免转义字符解析错误。

内容的提问来源于stack exchange,提问作者Anupam Krishna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 03:32:15