Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
817 views
in Technique[技术] by (71.8m points)

python - Rename downloaded files selenium

I'm using selenium to automatically download files in csv format from this page:

https://catalog.data.gov/dataset?tags=crime

This is the code I'm using:

profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.download.dir", '/home/luis/Desktop/data/')
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/csv")

driver = webdriver.Firefox(firefox_profile=profile)
driver.get(url)
time.sleep(2)
download_button = driver.find_element_by_xpath('//*[@id="content"]/div[2]/div[2]/section[1]/div[2]/ul/li[14]/div/ul/li[1]/a')
download_button.click()

Here the download folder is set:

profile.set_preference("browser.download.dir", '/home/luis/Desktop/data/')

How can I select the name with which the file is saved? Can be the name defined at the moment of the download?

I meant something like this:

For name in names:
    download_button = driver.find_element_by_xpath('//*[@id="content"]/div[2]/div[2]/section[1]/div[2]/ul/li[14]/div/ul/li[{}]/a'.format(name))
    download_button.click()
    save_file_as(name)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...