Selenium 上传文件:找不到文件

我有以下使用硒上传图像的方法。


public static void uploadSampleImage(StaticSeleniumDriver driver)

{

    File file = new File(System.getProperty("user.dir") + "/resources/images/" + SAMPLE_DOCUMENT_FILE_NAME);

    Utils.Log("file exists: " + file.exists());


    String imagePath = file.getAbsolutePath();

    WebElement input = driver.findElement(By.name("file"));

    input.sendKeys(imagePath);

}

这是提供文件路径的标准方式(如 Guru99 教程中所述)以上传文件。


在 Windows 上进行本地测试时效果很好

在 docker 容器(linux)中运行时它不起作用,出现此错误:

org.openqa.selenium.InvalidArgumentException:无效参数:找不到文件:/usr/src/app/resources/images/image2.png(会话信息:chrome=72.0.3626.81)(驱动程序信息:chromedriver=2.46.628388(4a34a70827ac54148e092aafb70504c4ea7ae926 ),platform=Linux 4.9.125-linuxkit x86_64) (警告:服务器没有提供任何堆栈跟踪信息)


这很奇怪,因为我确定给定目录中存在文件(在我上面的方法中,我正在检查文件是否存在并且日志清楚地确认了这一点)

http://img2.mukewang.com/62bd179800016cb213860360.jpg

慕工程0101907
浏览 380回答 2
2回答

红颜莎娜

因为RemoteWebDriver你必须设置文件检测器driver.setFileDetector(new LocalFileDetector());。你的代码:public static void uploadSampleImage(StaticSeleniumDriver driver){    driver.setFileDetector(new LocalFileDetector());    File file = new File(System.getProperty("user.dir") + "/resources/images/" + SAMPLE_DOCUMENT_FILE_NAME);    Utils.Log("file exists: " + file.exists());    String imagePath = file.getAbsolutePath();    WebElement input = driver.findElement(By.name("file"));    input.sendKeys(imagePath);}

斯蒂芬大帝

而不是在路径字符串中使用“/”,您可以使用File.separatorwhich 在引擎盖下自动处理操作系统级别的文件分隔符。使用它,您的代码变得独立于任何操作系统,它让 Java 负责根据操作系统使用什么分隔符,而不用担心它。所以第一行代码变成了:new File(System.getProperty("user.dir") + File.separator + "resources" + File.separator + "images" + File.separator + SAMPLE_DOCUMENT_FILE_NAME);其余部分保持不变。!!没有额外的头痛。😃
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java