程序在Eclipse可运行,导出为可运行Jar后抛出SessionNotCreatedException求助
解决导出可运行Jar后出现
org.openqa.selenium.SessionNotCreatedException的问题 你遇到的这个问题很典型——在IDE里运行正常,打包成Jar就报错,核心原因是FirefoxProfile在Jar包环境下的文件访问逻辑和本地IDE环境不一致,导致无法读取配置文件偏好。下面给你几个针对性的解决方案:
方案1:用FirefoxOptions替代FirefoxProfile(推荐)
FirefoxProfile是较旧的API,在Jar打包场景下容易出现文件访问问题,改用FirefoxOptions直接注入偏好设置可以彻底避开这个坑:
public void downloadProcess() throws Exception{ File dir = new File(getDir(), getStockId()+"-"+getFromYear()+"Q"+getFromQuarter()+"~"+getToYear()+"Q"+getToQuarter()); dir.mkdirs(); String path = new File(".").getCanonicalPath().toString(); System.setProperty("webdriver.gecko.driver", path+"\\geckodriver.exe"); // 用FirefoxOptions替代FirefoxProfile设置下载偏好 FirefoxOptions options = new FirefoxOptions(); // 指定下载目录为你创建的文件夹 options.addPreference("browser.download.dir", dir.getAbsolutePath()); options.addPreference("browser.download.folderList", 2); // 2表示使用自定义下载目录 // 根据你实际下载的文件类型添加MIME类型,避免弹出保存对话框 options.addPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf,application/vnd.ms-excel,text/csv"); // 禁用PDF预览(如果需要下载PDF的话) options.addPreference("pdfjs.disabled", true); // 初始化驱动 FirefoxDriver driver = new FirefoxDriver(options); // 后续业务逻辑... }
方案2:指定外部可访问的FirefoxProfile目录
如果你一定要保留FirefoxProfile的使用方式,不要依赖默认的系统Profile,而是创建一个自定义的Profile文件夹放在Jar外部,然后明确指定路径加载:
public void downloadProcess() throws Exception{ File dir = new File(getDir(), getStockId()+"-"+getFromYear()+"Q"+getFromQuarter()+"~"+getToYear()+"Q"+getToQuarter()); dir.mkdirs(); String path = new File(".").getCanonicalPath().toString(); System.setProperty("webdriver.gecko.driver", path+"\\geckodriver.exe"); // 加载Jar同目录下的自定义FirefoxProfile文件夹 File profileDir = new File(path + "\\custom-firefox-profile"); FirefoxProfile firefoxProfile = new FirefoxProfile(profileDir); // 继续设置你的偏好... FirefoxDriver driver = new FirefoxDriver(firefoxProfile); // 后续业务逻辑... }
打包Jar后,把custom-firefox-profile文件夹和Jar放在同一目录下即可,确保程序能读取到Profile文件。
方案3:排查路径问题
你代码里用new File(".").getCanonicalPath()获取当前路径,在Jar运行时这个路径可能和IDE里的预期不一致(比如可能指向系统临时目录或Jar的父目录),可以先打印路径确认:
String path = new File(".").getCanonicalPath().toString(); System.out.println("当前运行路径:" + path);
同时要注意:geckodriver.exe不能打包进Jar里,必须放在Jar外部的指定路径下,因为Selenium需要直接调用这个可执行文件,Jar内部的资源无法直接作为可执行程序调用。
内容的提问来源于stack exchange,提问作者林廷樹
相关产品推荐
相关产品推荐

