我用python和selenium一起编写了一个脚本,通过点击文件的链接从网页下载文件。当我运行我的脚本时,文件似乎是在预定义文件夹中下载的。
问题是,我找不到任何想法来重命名下载的文件。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)发布于 2019-02-04 09:24:42
我假设您下载的文件是在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)编辑:
但问题是事先没有这样的名字。
这让我想,如果我们能够找到一个文件已经下载成功,然后获取它的名称呢?But, wait. that is not possible!
或者是否有一种方法可以检测下载文件的名称?But, wait. You don't have control over the download file naming through selenium.
https://stackoverflow.com/questions/54513030
复制相似问题