SeleniumHQ / selenium

A browser automation framework and ecosystem.
https://selenium.dev
Apache License 2.0
29.74k stars 8.02k forks source link

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

Open limuyuan opened 3 weeks ago

limuyuan commented 3 weeks ago

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

github-actions[bot] commented 3 weeks ago

@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!

titusfortner commented 2 weeks ago

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.

github-actions[bot] commented 2 weeks ago

This issue is looking for contributors.

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