簡體   English   中英

Selenium 上傳文件:找不到文件[docker]

[英]Selenium upload file: file not found [docker]

我有以下使用 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 教程中所述)以上傳文件的標准方式。

  1. 在 windows 上本地測試時它工作正常
  2. 在 docker 容器 (linux) 中運行時它不工作,出現此錯誤:

org.openqa.selenium.InvalidArgumentException:參數無效:找不到文件:/usr/src/app/resources/images/image2.png(會話信息:chrome=72.0.3626.81)(驅動程序信息:chromedriver=2.46.628388(4a34a70827ac54148e092aafbea ),platform=Linux 4.9.125-linuxkit x86_64)(警告:服務器未提供任何堆棧跟蹤信息)

這很奇怪,因為我確定文件存在於給定目錄中(在我上面的方法中,我正在檢查文件是否存在並且日志清楚地確認了這一點)

在此處輸入圖像描述

歡迎任何建議,謝謝

對於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.separator而不是在路徑字符串中使用“/”,它會在后台自動處理操作系統級別的文件分隔符。 使用這個,你的代碼變得獨立於任何操作系統,它讓 Java 根據操作系統來處理使用什么分隔符,而不是你擔心它。

所以第一行代碼變成:

new File(System.getProperty("user.dir") + File.separator + "resources" + File.separator + "images" + File.separator + SAMPLE_DOCUMENT_FILE_NAME);

該行的 rest 保持不變。

.! 沒有額外的頭痛。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM