使用第三方工具AutoIt操作一些Webdriver无法操作的文件上传对象
1.安装AutoIt
a.下载地址:https://www.autoitscript.com/site/autoit/downloads/
b.备注:若使用64位操作系统,会弹出“64-bit Operating System Support"选择对话框,选择默认即可
2.安装AutoIt编辑器
a.下载地址:https://www.autoitscript.com/site/autoit-script-editor/downloads/
3.编写操作文件上传框体的AuotIt脚本
a.开始-AutoIt v3-SciTE/SciTE,启动AutoIt编辑器
b.输入脚本
#include <Constants.au3>
Send("F:\a.jpg")
Send("{ENTER}")
Send("{ENTER}")
解释:
调用两次Enter键,因为有些操作系统默认为中文输入法,输入文件路径"F:\a.jpg"时必须按Enter键;再次按Enter可以单击文件打开窗体的”打开“按钮
4.将脚本保存名为”test.au3",例如存放在D盘
5.开始-AutoIt v3,选择"Compile script to .exe(x64)"
Source路径选择D:\test.au3,点击"Convert",会生成D:\test.exe的可执行文件
Java语言版本的API实例代码:
@Test
public void testUploadFile() throws Exception {
WebElement fileInputBox = driver.findElement(By.id("file"));
fileInputBox.click();
Runtime.getRuntime().exec("d:/test.exe");
Thread.sleep(10000);
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("file"))); //判断页面是否关闭了文件选择框,重新显示上传文件元素
WebElement fileSubmitButton = driver.findElement(By.id("filesubmit"));
fileSubmitButton.click();
wait.until(ExpectedConditions.titleContains("文件上传成功"));
}