Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

naming a file when downloading with Selenium Webdriver

I see that you can set where to download a file to through Webdriver, as follows:

fp = webdriver.FirefoxProfile()

fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir",getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","text/csv")

browser = webdriver.Firefox(firefox_profile=fp)

But, I was wondering if there is a similar way to give the file a name when it is downloaded? Preferably, probably not something that is associated with the profile, as I will be downloading ~6000 files through one browser instance, and do not want to have to reinitiate the driver for each download.


Edit: Solution with code as suggested by the selected answer. Rename the file after each one is downloaded.

import os
os.chdir(SAVE_TO_DIRECTORY)
files = filter(os.path.isfile, os.listdir(SAVE_TO_DIRECTORY))
files = [os.path.join(SAVE_TO_DIRECTORY, f) for f in files] # add path to each file
files.sort(key=lambda x: os.path.getmtime(x))
newest_file = files[-1]
os.rename(newest_file, docName+".pdf")
like image 682
user1253952 Avatar asked Nov 09 '12 23:11

user1253952


People also ask

How do I name a file download?

Select File > Save As. Select where you want to save the file. Enter a new file name. Select Save.


1 Answers

I would suggest a little bit strange way: do not download files with the use of Selenium if possible.

I mean get the file URL and use urllib library to download the file and save it to disk in a 'manual' way. The issue is that selenium doesn't have a tool to handle Windows dialogs, such as 'save as' dialog. I'm not sure, but I doubt that it can handle any OS dialogs at all, please correct me I'm wrong. :)

Here's a tiny example:

import urllib
urllib.urlretrieve( "http://www.yourhost.com/yourfile.ext", "your-file-name.ext")

The only job for us here is to make sure that we handle all the urllib Exceptions. Please see http://docs.python.org/2/library/urllib.html#urllib.urlretrieve for more info.

like image 178
Pavel Daynyak Avatar answered Sep 19 '22 22:09

Pavel Daynyak