如何无需sleep检查Selenium自动化中「另存为」对话框的目标目录?
解决Selenium自动化下载时「另存为」对话框的目录校验问题
你编写的Selenium自动化下载脚本,在性能较差的电脑上会因为提前触发确认按钮导致文件存错目录。原代码依赖固定的time.sleep(10)等待,这种方式不够灵活,下面提供两种无需固定sleep的校验方案:
方案一:通过图像识别校验当前目录
利用「另存为」对话框路径栏的显示特征,提前截取正确目录的显示截图,然后轮询检测截图是否出现,确认目录正确后再执行后续操作:
- 先打开「另存为」对话框,导航到目标文件夹,截取路径栏中显示的目标目录截图,保存为
target_dir.png - 修改代码如下:
import pyautogui as pd import time # 提前准备好的目标目录截图路径 target_screenshot = "target_dir.png" # 粘贴路径并回车 pd.hotkey('ctrl', 'v') pd.hotkey('enter') # 轮询检测目录是否正确,confidence需要安装opencv-python while pd.locateOnScreen(target_screenshot, confidence=0.8) is None: time.sleep(0.5) # 短间隔重试,减少资源占用 # 确认目录正确后,输入文件名并确认 pd.typewrite(file_name.txt) pd.hotkey('enter')
注意:需要先安装
opencv-python才能使用confidence参数,执行pip install opencv-python即可。
方案二:读取路径栏文本对比校验
通过快捷键选中「另存为」对话框的路径栏,复制当前路径并和目标路径对比,一致后再继续:
import pyautogui as pd import pyperclip import time # 替换成你的目标文件夹绝对路径 target_path = "D:/Downloads/TargetFolder" # 粘贴路径并回车 pd.hotkey('ctrl', 'v') pd.hotkey('enter') # 循环校验当前路径是否匹配目标路径 while True: # 选中路径栏(Alt+D是Windows下的快捷键,Mac用Cmd+Shift+G) pd.hotkey('alt', 'd') # 复制当前路径 pd.hotkey('ctrl', 'c') current_path = pyperclip.paste().strip() if current_path == target_path: break time.sleep(0.5) # 输入文件名并确认 pd.typewrite(file_name.txt) pd.hotkey('enter')
这个方案无需截图,直接通过文本对比校验,兼容性更强,适合不同系统或对话框样式的场景。
内容的提问来源于stack exchange,提问作者atom77
相关产品推荐
相关产品推荐

