Skip to content
Advertisement

Selenium give file name when downloading

I am working with a selenium script where I am trying to download a Excel file and give it a specific name. This is my code:

Is there anyway that I can give the file being downloaded a specific name ?

Code:

#!/usr/bin/python
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

profile = FirefoxProfile()
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain, application/vnd.ms-excel, text/csv, text/comma-separated-values, application/octet-stream")
profile.set_preference("browser.download.dir", "C:\Downloads" )
browser = webdriver.Firefox(firefox_profile=profile)

browser.get('https://test.com/')
browser.find_element_by_partial_link_text("Excel").click() # Download file

Advertisement

Answer

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"))
Advertisement