selenium icon indicating copy to clipboard operation
selenium copied to clipboard

[🐛 Bug]: Cannot download file with Javascript. WebDriverError: Cannot find file [xxx] in directory xxxx

Open limuyuan opened this issue 1 year ago • 3 comments

What happened?

When I'm trying to download a file with Javascript driver.downloadFile, it always return error message that the downloaded file cannot be found, but I did find the downloaded file in the same folder as expected.

How can we reproduce the issue?

Exception will be thrown after executing await driver.downloadFile(files, targetDirectory);

const webdriver = require("selenium-webdriver");
const path = require('path');
const os = require('os');
const { By } = webdriver;
const firefox = require('selenium-webdriver/firefox');
const options = new firefox.Options()

async function runTest_DownloadFile() {
  try {
    options.set('se:downloadsEnabled', true);

    let driver = new webdriver.Builder()
    .usingServer("http://192.168.0.116:4444")
    .forBrowser("firefox")
    .setFirefoxOptions(options)
    .build()

    const fileNames = ['20MB.bin'];

    driver.get("https://myjob.page/tools/test-files").then(async () => {
      downloadLink = await driver.findElement(By.xpath('/html/body/main/div/div/div[1]/a[5]'));
      await downloadLink.click();

      await waitForDownloadableFile(driver, fileNames);
      files = await driver.getDownloadableFiles();

      if (files.sort().toString() === fileNames.sort().toString()) {
        console.log(JSON.stringify({ status: "passed", message: "Test passed successfully" }));
      } else {
        console.log(JSON.stringify({ status: 'failed', message: 'Files mismatch!' }));
      }

      const targetDirectory = path.join(os.tmpdir(), 'nodejs_downloaded');
      await driver.downloadFile(files, targetDirectory);

      try {
        await driver.quit();
      } catch (error) {
        if (error.message != "success") {
          console.error('Error during test execution:', error);
          console.log(JSON.stringify({ status: "failed", message: error.message }));
        }
      }
      console.log(JSON.stringify({ status: "passed", message: "Test passed successfully" }));
    });
  } catch (error) {
    if (driver) {
      await driver.quit();
    }
    console.error('Error during test execution:', error);
    console.log(JSON.stringify({ status: "failed", message: error.message }));
  }
}

// Function to wait for downloadable files to include the desired file
async function waitForDownloadableFile(driver, fileNames, interval = 3000, maxAttempts = 10) {
  let attempt = 0;
  while (attempt < maxAttempts) {
    const files = await driver.getDownloadableFiles();
    if (fileNames.every(fileName => files.includes(fileName))) {
      return;
    }
    await new Promise(resolve => setTimeout(resolve, interval));
    attempt++;
  }
  throw new Error(`Timeout: Files '${fileNames}' not found after ${maxAttempts} attempts`);
}

runTest_DownloadFile();

Relevant log output

Uncaught WebDriverError WebDriverError: Cannot find file [[20MB.bin]] in directory C:\Users\morris\AppData\Local\Temp\uuid13450316481929214739243743f-a595-442a-a00c-628ac48d6152\download4510867298970579268.
Build info: version: '4.21.0', revision: '79ed462ef4'
System info: os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '17.0.5'
Driver info: driver.version: unknown
    at throwDecodedError (d:\GitHub\Li-MuYuan\Selenium-Scripts\node-js\node_modules\selenium-webdriver\lib\error.js:521:15)
    at parseHttpResponse (d:\GitHub\Li-MuYuan\Selenium-Scripts\node-js\node_modules\selenium-webdriver\lib\http.js:514:13)
    at execute (d:\GitHub\Li-MuYuan\Selenium-Scripts\node-js\node_modules\selenium-webdriver\lib\http.js:446:28)
    at processTicksAndRejections (internal/process/task_queues:95:5)

Operating System

Windows 10

Selenium version

Selenium 4.21.0

What are the browser(s) and version(s) where you see this issue?

Firefox 126

What are the browser driver(s) and version(s) where you see this issue?

Gecko Driver 0.34.0

Are you using Selenium Grid?

No response

limuyuan avatar Jun 08 '24 15:06 limuyuan

@limuyuan, thank you for creating this issue. We will troubleshoot it as soon as we can.


Info for maintainers

Triage this issue by using labels.

If information is missing, add a helpful comment and then I-issue-template label.

If the issue is a question, add the I-question label.

If the issue is valid but there is no time to troubleshoot it, consider adding the help wanted label.

If the issue requires changes or fixes from an external project (e.g., ChromeDriver, GeckoDriver, MSEdgeDriver, W3C), add the applicable G-* label, and it will provide the correct link and auto-close the issue.

After troubleshooting the issue, please add the R-awaiting answer label.

Thank you!

github-actions[bot] avatar Jun 08 '24 15:06 github-actions[bot]

Looking at this: Cannot find file [[20MB.bin]] Looks like this might be a typing issue where we are looking for an array of the string instead of the string.

titusfortner avatar Jun 11 '24 14:06 titusfortner

This issue is looking for contributors.

Please comment below or reach out to us through our IRC/Slack/Matrix channels if you are interested.

github-actions[bot] avatar Jun 11 '24 14:06 github-actions[bot]

HI @limuyuan ,

The await driver.downloadFile(fileName, targetDirectory) function expects a single file name (string), but an array of file names is currently being passed.

You should handle each file name individually. For example:

const webdriver = require("selenium-webdriver");
const path = require('path');
const os = require('os');
const { By } = webdriver;
const firefox = require('selenium-webdriver/firefox');
const options = new firefox.Options()

async function runTest_DownloadFile() {
 try {
   options.set('se:downloadsEnabled', true);

   let driver = new webdriver.Builder()
     .usingServer("http://localhost:4444")
     .forBrowser("firefox")
     .setFirefoxOptions(options)
     .build()

   const fileName = '20MB.bin';

   driver.get("https://myjob.page/tools/test-files").then(async () => {
     downloadLink = await driver.findElement(By.xpath('/html/body/main/div/div/div[1]/a[5]'));
     await downloadLink.click();

     await waitForDownloadableFile(driver, fileName);
     const targetDirectory = path.join(os.tmpdir(), 'nodejs_downloaded');
     await driver.downloadFile(fileName, targetDirectory);

     try {
       await driver.quit();
     } catch (error) {
       if (error.message !== "success") {
         console.error('Error during test execution:', error);
         console.log(JSON.stringify({ status: "failed", message: error.message }));
       }
     }
     console.log(JSON.stringify({ status: "passed", message: "Test passed successfully" }));
   });
 } catch (error) {
   if (driver) {
     await driver.quit();
   }
   console.error('Error during test execution:', error);
   console.log(JSON.stringify({ status: "failed", message: error.message }));
 }
}

// Function to wait for downloadable files to include the desired file
async function waitForDownloadableFile(driver, fileName, interval = 3000, maxAttempts = 10) {
 let attempt = 0;
 while (attempt < maxAttempts) {
   const files = await driver.getDownloadableFiles();
   if (files.includes(fileName)) {
     return;
   }
   await new Promise(resolve => setTimeout(resolve, interval));
   attempt++;
 }
 throw new Error(`Timeout: Files '${fileName}' not found after ${maxAttempts} attempts`);
}
runTest_DownloadFile();

Hope this helps!

harsha509 avatar Aug 06 '24 13:08 harsha509

I am closing this because we did not get a reply from the OP.

diemol avatar Aug 21 '24 06:08 diemol

This issue has been automatically locked since there has not been any recent activity since it was closed. Please open a new issue for related bugs.

github-actions[bot] avatar Sep 20 '24 22:09 github-actions[bot]