在Python-Selenium中自动下载文件后,如何以编程方式重命名该文件?

问题描述 投票:-1回答:2

我有一个Selenium(Chrome)脚本,该脚本会转到URL并顺序下载一堆文件。但是这些名称都是乱七八糟的,因此Selenium和Chrome都无法控制下载文件的名称。因此,我想做的是在下载目录中监视所有已创建的新文件,然后在创建时使用我自己选择的名称对其进行重命名。

我该如何处理?我听说watchdog是创建和记录EventListener的好软件包。但是,当触发on_created事件时,如何动态地向处理程序传递特定名称? watchdog是正确的方法还是其他可行的解决方案?

注意:我确实尝试过使用glob抓取目录中的所有文件,然后通过比较创建时间更新最新文件的名称,但是这会导致逻辑错误,因为它混淆了文件名,以防万一在执行此方法时尚未下载新文件。我已经为该方法附上了下面的代码。

def __rename_downloaded_file(self, filename: str):
    """Rename the latest download file to the given name"""
    # TODO create a listener instead of the while loop
    while True:
        # keep looping in case there are no file in directory.
        list_of_files = glob.glob(f"{self.download_path}\\*.pdf")
        if len(list_of_files) > 0:
            break
    latest_file = max(list_of_files, key=os.path.getctime)
    print(latest_file)
    head, _ = os.path.split(latest_file)
    new_filename = os.path.join(head, filename+'.pdf')
    print(new_filename)
    os.rename(latest_file, new_filename)
python-3.x selenium-webdriver listener file-rename python-watchdog
2个回答
0
投票

您是否试图等待文件下载。如果您这样做,则可以通过max(list_of_files,key = os.path.getctime)获取最新文件,并更改最新文件名。文件更改后,您可能已经开始下载其他文件


0
投票

答案是here

© www.soinside.com 2019 - 2024. All rights reserved.