我已经写在与硒结合的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)
我假设你已经下载下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.