Selenium Give File Name When Downloading

Selenium give file name when downloading

You cannot specify name of download file through selenium. However, you can download the file, find the latest file in the downloaded folder, and rename as you want.

Note: borrowed methods from google searches may have errors. but you get the idea.

import os
import shutil
filename = max([Initial_path + "\\" + f for f in os.listdir(Initial_path)],key=os.path.getctime)
shutil.move(filename,os.path.join(Initial_path,r"newfilename.ext"))

How to get the downloaded file name? (Selenium)

Based on OP comment above that,

I think trimming the .1637344008787 part is enough since every file name has this type of part only.

You can do the following:

a = "BEHR SDS.1637344008787.pdf"
orginal_file_name = a.split('.')[0] + '.pdf'
print(orginal_file_name)

Now I have hardcoded the file name, you should go to directory and look for the latest file which has been downloaded.

Rename downloaded files selenium

You don't have control over the download file naming through selenium.

What you can do is to use a directory watcher/observer to detect when the file is downloaded and then rename it accordingly. Please see this answer containing more follow-up details.

How to specify name of file being downloaded from chrome in Selenium Java testing framework

Found solution in this topic Selenium give file name when downloading answer from @supputuri
It is not possible to give the name to downloaded file, but below is the code how to get the name of downloaded file.

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;

}

How to change saved PDF page name with Selenium + Chromedrive

Change download.default_directory to savefile.default_directory so your saving location works.

Sadly I think we can't change the filename before download, but you can rename your file after download, by renaming the latest file in download folder:

import os    
import shutil
download_folder = "C:\\Users\\username\\Downloads\\Test"
filename = max([download_folder + "\\" + f for f in os.listdir(Initial_path)],key=os.path.getctime)
shutil.move(filename,os.path.join(Initial_path,r"newPDFName.pdf"))

naming a file when downloading with Selenium Webdriver

I do not know if there is a pure Selenium handler for this, but here is what I have done when I needed to do something with the downloaded file.

  1. Set a loop that polls your download directory for the latest file that does not have a .part extension (this indicates a partial download and would occasionally trip things up if not accounted for. Put a timer on this to ensure that you don't go into an infinite loop in the case of timeout/other error that causes the download not to complete. I used the output of the ls -t <dirname> command in Linux (my old code uses commands, which is deprecated so I won't show it here :) ) and got the first file by using

    # result = output of ls -t
    result = result.split('\n')[1].split(' ')[-1]
  2. If the while loop exits successfully, the topmost file in the directory will be your file, which you can then modify using os.rename (or anything else you like).

Probably not the answer you were looking for, but hopefully it points you in the right direction.

Selenium Python Download popup pdf with specific filename

Add your options before launching Chrome and then specify the chrome_options parameter.

download_dir = "/Users/ugur/Downloads/"
options = webdriver.ChromeOptions()

profile = {"plugins.plugins_list": [{"enabled": False, "name": "Chrome PDF Viewer"}],
"download.default_directory": download_dir,
"download.extensions_to_open": "applications/pdf"}
options.add_experimental_option("prefs", profile)

driver = webdriver.Chrome(
executable_path="/Users/ugur/Downloads/chromedriver",
chrome_options=options
)

To answer your second question:

May I ask how to specify the filename as well?

I found this: Selenium give file name when downloading

What I do is:

file_name = ''
while file_name.lower().endswith('.pdf') is False:
time.sleep(.25)
try:
file_name = max([download_dir + '/' + f for f in os.listdir(download_dir)], key=os.path.getctime)
except ValueError:
pass


Related Topics



Leave a reply



Submit