我用python与硒结合编写了一个脚本,以通过单击该文件的链接来从网页下载文件。当我运行脚本时,该文件似乎已下载到预定义的文件夹中。
问题是我找不到重命名下载文件的想法。 FYC该文件夹中可能有多个文件。我想将下载的文件重命名为脚本中的变量newname
。
如何重命名从文件夹下载的文件?
这是我到目前为止写的:
import os
from selenium import webdriver
url = "https://www.online-convert.com/file-format/docx"
folder_location = r"C:\Users\WCS\Desktop\file_storage"
newname = "document.docx"
def download_n_rename_file(link):
driver.get(link)
driver.find_element_by_css_selector("a[href$='example_multipage.docx']").click()
#how to rename the downloaded file to "document.docx"
#os.rename()
if __name__ == '__main__':
chromeOptions = webdriver.ChromeOptions()
prefs = {'download.default_directory': folder_location}
chromeOptions.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(chrome_options=chromeOptions)
download_n_rename_file(url)
答案 0 :(得分:0)
我假设您下载的文件以example_multipage.docx
命名:
import os
from selenium import webdriver
url = "https://www.online-convert.com/file-format/docx"
folder_location = r"C:\Users\WCS\Desktop\file_storage"
newname = "document.docx"
def download_n_rename_file(link):
driver.get(link)
driver.find_element_by_css_selector("a[href$='example_multipage.docx']").click()
# To rename the downloaded file to "document.docx"
os.rename('example_multipage.docx',newname)
if __name__ == '__main__':
chromeOptions = webdriver.ChromeOptions()
prefs = {'download.default_directory': folder_location}
chromeOptions.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(chrome_options=chromeOptions)
download_n_rename_file(url)
编辑:
OP:但是问题在于事先没有这样的现有名称。
这让我想,如果成功下载文件然后找到文件名,该怎么办? But, wait. that is not possible!
还是有一种方法可以检测下载文件的名称? But, wait. You don't have control over the download file naming through selenium.