How to get the url or filename being downloaded now?

Question:

After click the button, how to know the downloading url(with the filename), or

how to know the filename(complete with extension) being downloaded? One problem is, e.g. the downloaded file some have .csv extension, some without.

e.g. I would like to rename it unified. (pls. don’t wanna go to the D/L DIR, find the file and rename it)

from selenium import webdriver
from selenium.webdriver.firefox.options import Options 
...
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv')
...
driver = webdriver.Firefox(profile, options=opts, executable_path=FIREFOX_GOCKO_DRIVER_PATH)

driver.get(url)
driver.find_element_by_id(Button).click()

print("The file being downloaded is... ", ??? )
print("File is being downloaded from...", ?url?)
Asked By: NegaOverflow

||

Answers:

Here is the simple solution to get the latest downloaded file name and url.

Note: considering the file download is completed before running this below code.

If you want the script wait until the download completed, then check the getDownLoadedFileName method at the end of the answer.

# open a new tab
driver.execute_script("window.open()")
# switch to new tab
driver.switch_to.window(driver.window_handles[-1])
# navigate to chrome downloads
driver.get('chrome://downloads')
# get the latest downloaded file name
fileName = driver.execute_script("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content  #file-link').text")
# get the latest downloaded file url
sourceURL = driver.execute_script("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content  #file-link').href")
# print the details
print(fileName)
print (sourceURL)
# close the downloads tab2
driver.close()
# switch back to main window
driver.switch_to.window(driver.window_handles[0])

if you want you can make it as a method and call where ever it’s required.

Edit: Don’t worry if you have to wait until the download completed

You can relay on chrome downloads status, check the below method.

Just call the below method in you code while getting the file name

def getDownLoadedFileName(waitTime):
    downloadsList = driver.execute_script("return document.querySelector('downloads-manager').shadowRoot")
    endTime = time.time()+waitTime
    while True:
        try:
            fileName = driver.execute_script("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content  #file-link').text")
            if fileName:
                return fileName
        except:
            pass
        time.sleep(1)
        if time.time() > endTime:
            break

You can call this method as shown below.

# wait until the download completes and get the file name
fileName = getDownLoadedFileName(180)
print(fileName)

Firefox: Use the below method for firefox.

def getDownLoadedFileName(waitTime):
    driver.execute_script("window.open()")
    WebDriverWait(driver,10).until(EC.new_window_is_opened)
    driver.switch_to.window(driver.window_handles[-1])
    driver.get("about:downloads")

    endTime = time.time()+waitTime
    while True:
        try:
            fileName = driver.execute_script("return document.querySelector('#contentAreaDownloadsView .downloadMainArea .downloadContainer description:nth-of-type(1)').value")
            if fileName:
                return fileName
        except:
            pass
        time.sleep(1)
        if time.time() > endTime:
            break

Java + Chrome: In case if you are looking for java implementation.

Here is the method in java.

public String waitUntilDonwloadCompleted(WebDriver driver) throws InterruptedException {
      // Store the current window handle
      String mainWindow = driver.getWindowHandle();

      // open a new tab
      JavascriptExecutor js = (JavascriptExecutor)driver;
      js.executeScript("window.open()");
     // switch to new tab
    // Switch to new window opened
      for(String winHandle : driver.getWindowHandles()){
          driver.switchTo().window(winHandle);
      }
     // navigate to chrome downloads
      driver.get("chrome://downloads");

      JavascriptExecutor js1 = (JavascriptExecutor)driver;
      // wait until the file is downloaded
      Long percentage = (long) 0;
      while ( percentage!= 100) {
          try {
              percentage = (Long) js1.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#progress').value");
              //System.out.println(percentage);
          }catch (Exception e) {
            // Nothing to do just wait
        }
          Thread.sleep(1000);
      }
     // get the latest downloaded file name
      String fileName = (String) js1.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content #file-link').text");
     // get the latest downloaded file url
      String sourceURL = (String) js1.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content #file-link').href");
      // file downloaded location
      String donwloadedAt = (String) js1.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div.is-active.focus-row-active #file-icon-wrapper img').src");
      System.out.println("Download deatils");
      System.out.println("File Name :-" + fileName);
      System.out.println("Donwloaded path :- " + donwloadedAt);
      System.out.println("Downloaded from url :- " + sourceURL);
     // print the details
      System.out.println(fileName);
      System.out.println(sourceURL);
     // close the downloads tab2
      driver.close();
     // switch back to main window
      driver.switchTo().window(mainWindow);
      return fileName;
  }

This is how to call this in your java script.

// download triggering step 
downloadExe.click();
// now waituntil download finish and then get file name
System.out.println(waitUntilDonwloadCompleted(driver));
Answered By: supputuri

Inspired by the work of @supputuri here is my implementation of waitUntilDownloadCompleted() written in C#.

    public static void waitUntilDownloadCompleted(this IWebDriver driver, string newFileName)
    {
        string scriptFileName, scriptPercentage, downloadsURL, fileName;

        switch (driver.GetType().ToString())
        {
            case "OpenQA.Selenium.Chrome.ChromeDriver":
                // sourceURL: use "document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content #file-link').href"
                // downloadLocation: use "document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div.is-active.focus-row-active #file-icon-wrapper img').src"
                scriptFileName = "return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content #file-link').text";
                scriptPercentage = "return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#progress').value";
                downloadsURL = "chrome://downloads";
                break;

            case "OpenQA.Selenium.Firefox.FirefoxDriver":
                scriptFileName = "return document.querySelector('#contentAreaDownloadsView description:nth-of-type(1)').value";
                scriptPercentage = "return document.querySelector('#contentAreaDownloadsView richlistitem.download:nth-child(1) > hbox:nth-child(1) > vbox:nth-child(2) > progress:nth-child(2)').value";
                downloadsURL = "about:downloads";
                break;

            default:
                throw new NotImplementedException(string.Format("Driver {0} is not supported", driver.GetType().ToString()));
        }

        // Store the current window handle
        string mainWindow = driver.CurrentWindowHandle;

        // open new tab and switch focus
        IJavaScriptExecutor js = driver as IJavaScriptExecutor;
        driver.SwitchTo().Window(mainWindow);
        js.ExecuteScript("window.open();");
        driver.SwitchTo().Window(driver.WindowHandles.Last());

        // navigate to downloads
        driver.Navigate().GoToUrl(downloadsURL);

        // wait until download is complete
        IJavaScriptExecutor js1 = driver as IJavaScriptExecutor;
        long percentage = 0;
        while (percentage != 100)
        {
            try
            {
                percentage = (long)js1.ExecuteScript(scriptPercentage);
            }
            catch (Exception)
            {
                // Nothing to do just wait
            }
            Thread.Sleep(1000);
        }

        // get the latest downloaded file name
        fileName = Path.Combine(Environment.ExpandEnvironmentVariables("%USERPROFILE%"), "Downloads", (string)js1.ExecuteScript(scriptFileName));

        // close the downloads tab
        driver.Close();

        // switch back to main window
        driver.SwitchTo().Window(mainWindow);
        driver.wait_A_Moment(timeDelay);

        // delete if new file exists
        if (File.Exists(newFileName))
            File.Delete(newFileName);

        // rename downloaded file
        File.Move(fileName, newFileName);
        File.Delete(fileName);
    }
Answered By: Gene Yuss
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.