最近在web自动化脚本编写过程中,碰到导出功能的测试,目前我们自动化只要求做到单击导出按钮,然后检查文件是否导出成功,关键过程如下:
1、修改chrome的option使文件能自动无阻的下载到电脑Downloads目录:
简化后的关键代码:
download_folder = os.path.join(os.path.expanduser("~"), "Downloads")
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--unsafely-treat-insecure-origin-as-secure=http://192.168.209.105:9099")
preferences = {"download.default_directory": download_folder,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True
}
chrome_options.add_experimental_option("prefs", preferences)
driver = webdriver.Chrome(chrome_options=chrome_options)
2、导出完成后,检查目标文件名的文件在最近多少秒是否生成
def check_export_file_is_exist(file_name, until_now_time=180):
"""
用于检查导出文件是否存在(在当前时刻往前多少秒内在下载文件夹下有创建目标名称的文件)
:param file_name: 导出文件的文件名(注意:不包含文件后缀)
:param until_now_time: 检查时间范围,当前时刻往前多少秒
:return:存在返回True,不存在返回False
"""
current_time = time.time()
# 获取当前电脑的下载目录
download_folder = os.path.join(os.path.expanduser("~"), "Downloads")
for file in os.listdir(download_folder):
file_path = os.path.join(download_folder, file)
if os.path.isfile(file_path) and file_name in os.path.splitext(file)[0]:
creat_time = os.path.getctime(file_path)
if current_time - creat_time <= until_now_time:
return True
logger.error(f"下载文件夹下不窜在{until_now_time}秒内生成的文件名包含'{file_name}'的文件")
return False