简体   繁体   中英

Downloading csv file using selenium python and deleting it

Is it possible to Download a csv file using selenium python and then deleting it or just download the file temporary only?

This is the code i am using to download the csv file

fp = webdriver.FirefoxProfile()

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

fp.set_preference("pdfjs.disabled", True)

browser = webdriver.Firefox(firefox_profile=fp)

You can mention the path to your file and use os.remove() to remove/delete the file.

EDIT: If you wish to fetch the name of the file which you have downloaded (I don't think selenium has added this functionality yet) you can try checking the difference in the directory listing before and after downloading the file by using os.listdir() .

import os

before = os.listdir('/home/jason/Downloads')

# Download the file using Selenium here

after = os.listdir('/home/jason/Downloads')
change = set(after) - set(before)
if len(change) == 1:
    file_name = change.pop() #file name stored as string
else:
    print "More than one file or no file downloaded"

I have added one line of code and the following solution works

import os

before = os.listdir('/home/jason/Downloads')

# Download the file using Selenium here

after = os.listdir('/home/jason/Downloads')
change = set(after) - set(before)
if len(change) == 1:
    file_name = change.pop() #file name stored as string
    os.remove(file_name) 
else:
    print "More than one file or no file downloaded"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM