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
相关产品推荐
相关产品推荐

