5

Is there anyway I can get the last downloaded file using selenium. Currently I am downloading an Excel file using selenium, I need to get that file and read it. the reading part is covered, but I need the downloaded file path and file name in order to read it. So far i haven't found anything which can help. I am looking mainly for a google chrome solution, but firefox works too.

Thanks in advance

jnam
  • 71
  • 1
  • 1
  • 3

4 Answers4

3
import os
import glob

home = os.path.expanduser("~")
downloadspath=os.path.join(home, "Downloads")
list_of_files = glob.glob(downloadspath+"\*.pptx") # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)

Simplified solution to get the path to last file in Downloads folder. The above code will get path of the latest .pptx file in Downlodas. Change the extension as required. Or else you can chose not to specify the extension

anandhu
  • 686
  • 2
  • 13
  • 40
2

You can save your download to a fix location by using the profile. Check these discussions:

Downloading file to specified location with Selenium and python
Access to file download dialog in Firefox

As you have mentioned that you have covered the reading part. You can read it from that fixed location.

Community
  • 1
  • 1
Chandan Nayak
  • 10,117
  • 5
  • 26
  • 36
2

Below is the code snippet that can help resolve the above query:

**Changes in driver file:**

protected File downloadsDir = new File("");
if (browser.equalsIgnoreCase("firefox")) 
{
    downloadsDir = new File(System.getProperty("user.dir") + File.separatorChar + "downloads");
    if (!downloadsDir.exists()) 
     {
        boolean ddCreated = downloadsDir.mkdir();
        if (!ddCreated) {
            System.exit(1);
        }
    }
}


/*Firefox browser profile*/
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList", 2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.dir", downloadsDir.getAbsolutePath());
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/plain,application/octet-stream");

**Empty the download directory[Can be implemented as @BeforeClass]:**

public void emptyDownloadsDir()
{
    // Verify downloads dir is empty, if not remove all files.
    File[] downloadDirFiles = downloadsDir.listFiles();
    if (downloadDirFiles != null) {
        for (File f : downloadDirFiles) {
            if (f.exists()) {
                boolean deleted = FileUtility.delete(f);
                assertTrue(deleted, "Files are not deleted from system local directory" + downloadsDir + ", skipping the download tests.");
            }
        }
    }
}


**Check the Latest downloaded file:**

/*Test file*/
protected static String EXCEL_FILE_NAME= Test_Excel_File.xls;

protected static int WAIT_IN_SECONDS_DOWNLOAD = 60;

// Wait for File download.
int counter = 0;
while (counter++ < WAIT_IN_SECONDS_DOWNLOAD && (downloadsDir.listFiles().length != 1 || downloadsDir.listFiles()[0].getName().matches(EXCEL_FILE_NAME))) {
    this.wait(2);
}

// Verify the downloaded File by comparing name.
File[] downloadDirFiles = downloadsDir.listFiles();
String actualName = null;
for (File file : downloadDirFiles) {
    actualName = file.getName();
    if (actualName.equals(EXCEL_FILE_NAME)) {
        break;
    }
}
assertEquals(actualName, EXCEL_FILE_NAME, "Last Downloaded File name does not matches.");
QASource
  • 65
  • 1
1

Note, Shared answer is specific to Chrome Browser and will ONLY return LATEST downloaded file. But we can modify accordingly it for other browsers and for all files as well.

Let say, how we test latest downloaded file in browser.

  1. In existing test browser Open NewTab Window
  2. Go to downloads (chrome://downloads/)
  3. Check if expected file is there or not

Now same thing in selenium using java

driver.get("chrome://downloads/");
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = (WebElement) js.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#mainContainer > iron-list > downloads-item').shadowRoot.querySelector('#content')");
String latestFileName=  element.getText();
  • Or something like this in the execcuteScript to select all the files: `return [...document.querySelector('downloads-manager').shadowRoot.querySelector('#mainContainer > iron-list').getElementsByTagName("downloads-item")].map((el)=>el.shadowRoot.getElementById("file-link").getAttribute("href"))` – Александр М Dec 28 '22 at 10:22