Python Selenium中Chromedriver执行后自动关闭及SSL错误求助
问题解决:ChromeDriver窗口自动关闭+SSL握手错误
一、解决Chrome窗口执行后立即关闭的问题
脚本执行完毕后,Python会自动销毁driver对象,导致Chrome窗口关闭。有两种简单的解决方式:
方法1:添加阻塞代码
在脚本末尾加上input(),让程序等待用户输入后再结束:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager import time path = "X:/test/chromedriver.exe" s = Service(path) driver = webdriver.Chrome(service=s) url = "https://www.nike.com/in/w/mens-shoes-nik1zy7ok" driver.get(url) time.sleep(4) height = driver.execute_script("return document.body.scrollHeight") while True: driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") time.sleep(3) new_height = driver.execute_script("return document.body.scrollHeight") if height == new_height: break height = new_height # 新增:等待用户输入,防止窗口自动关闭 input("按任意键关闭窗口...")
方法2:设置ChromeOptions的detach参数
初始化driver时配置detach=True,让Chrome窗口在脚本结束后保持打开:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options # 新增导入 from webdriver_manager.chrome import ChromeDriverManager import time path = "X:/test/chromedriver.exe" # 配置Chrome选项 chrome_options = Options() chrome_options.add_experimental_option("detach", True) s = Service(path) driver = webdriver.Chrome(service=s, options=chrome_options) # 传入options url = "https://www.nike.com/in/w/mens-shoes-nik1zy7ok" driver.get(url) time.sleep(4) height = driver.execute_script("return document.body.scrollHeight") while True: driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") time.sleep(3) new_height = driver.execute_script("return document.body.scrollHeight") if height == new_height: break height = new_height
二、解决SSL握手错误
日志中的ssl_client_socket_impl.cc错误,通常是ChromeDriver与Chrome版本不兼容,或者SSL证书验证问题导致的,可按以下步骤处理:
确保ChromeDriver与Chrome版本匹配:手动指定
path的驱动可能和当前Chrome版本不兼容,建议启用你注释掉的webdriver-manager代码,它会自动下载匹配版本的ChromeDriver:# 替换原driver初始化代码 driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)忽略SSL证书错误:在ChromeOptions中添加参数跳过SSL验证:
chrome_options = Options() chrome_options.add_experimental_option("detach", True) # 新增忽略SSL错误的参数 chrome_options.add_argument("--ignore-certificate-errors") chrome_options.add_argument("--ignore-ssl-errors")更新Chrome浏览器:确保你的Chrome是最新版本,避免因版本过旧导致的兼容性问题。
内容的提问来源于stack exchange,提问作者Subhrajit Samanta
相关产品推荐
相关产品推荐

