如何通过pywinauto获取Outlook下载文件的文件名或绝对路径?
解决方法
方法1:监控下载文件夹获取最新文件
直接轮询Downloads文件夹,追踪最新创建/修改的文件,这是最直接的方案,无需依赖UI控件定位:
import os import time from pathlib import Path def get_latest_download(): downloads_path = str(Path.home() / "Downloads") # 获取文件夹内所有文件,过滤掉子文件夹 files = [os.path.join(downloads_path, f) for f in os.listdir(downloads_path) if os.path.isfile(os.path.join(downloads_path, f))] if not files: return None # 按创建时间倒序排序,取第一个即为最新文件 latest_file = max(files, key=os.path.getctime) return latest_file # 点击Outlook链接后调用,根据下载速度调整等待时间 time.sleep(5) latest_file_path = get_latest_download() if latest_file_path: print(f"最新下载文件路径:{latest_file_path}")
如果需要实时监控文件夹变化,可使用watchdog库:
from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler import time from pathlib import Path class DownloadHandler(FileSystemEventHandler): def on_created(self, event): if not event.is_directory: print(f"新下载文件:{event.src_path}") # 此处可触发后续回放操作 downloads_path = str(Path.home() / "Downloads") event_handler = DownloadHandler() observer = Observer() observer.schedule(event_handler, downloads_path, recursive=False) observer.start() # 保持监听直到捕获到新文件 try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
方法2:捕获Outlook下载弹窗提取文件名
Outlook下载时会弹出提示对话框,可通过pywinauto定位弹窗并提取文件名:
from pywinauto import Application from pathlib import Path # 连接到已打开的Outlook应用 app = Application(backend="uia").connect(title_re="Outlook") # 点击链接后等待下载弹窗出现 download_dialog = app.window(title_re=".*下载.*", control_type="Window").wait('visible', timeout=10) # 提取弹窗中的文件名(控件标识需根据Outlook版本调整) file_name = download_dialog.static_text(auto_id="FileNameControl").get_value() full_path = str(Path.home() / "Downloads" / file_name) print(f"下载文件路径:{full_path}")
若不确定控件标识,可先打印弹窗的所有控件信息:
download_dialog.print_control_identifiers()
方法3:读取Outlook下载历史(备选)
此方法兼容性较差,仅作为前两种方案的补充:Outlook的下载记录会存储在注册表中,路径通常为HKEY_CURRENT_USER\Software\Microsoft\Office\<版本号>\Outlook\Options\Download,可通过Python的winreg模块读取并解析其中的内容。
内容的提问来源于stack exchange,提问作者Data Geek
相关产品推荐
相关产品推荐

