上传文件是每个自动化测试同学会遇到,而且可以说是面试必考的问题,标准控件我们一般用sendkeys()就能完成上传,但是我们的测试网站的上传控件一般为自己封装的,用传统的上传已经不好用了,也就是说用selenium的APi已经无法完成上传操作了,这时我们就要借用第三方工具Autolt来完成上传文件的操作。
1、下载autolt 官网:https://www.autoitscript.com/site/autoit/downloads/,请自行下载 也可以百度下载绿色版,免安装,笔者就是绿色版,下面案例都以绿色版进行讲解 附百度网盘:链接: https://pan.baidu.com/s/1szmGK7wudsXKkH5xkEOnOQ 提取码: dysb 2、下载后解压到指定目录 3、被测网页HTML代码如下
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>上传文件演示案例</title>
</head>
<body>
<div class="row-fluid">
<div class="span6 well">
<h3>upload File</h3>
<input id="upload" type="file" name="file" />
</div>
</div>
</body>
</html>
编写上传脚本 1、找到解压目录,双击AU3TOOL.exe,打开界面是写脚本用的
2、双击Au3Info.exe,打开定位工具界面
3、在文件中输入以下代码:注意括号内的参数 ,下一步中将会讲如何获取参数
ControlFocus("title1","","Edit1");
WinWait("[CLASS:#32770]","",10);
ControlSetText("title1","","Edit1","文件地址");
Sleep(2000);
ControlClick("title2","","Button1");
4、获取上一步中(前3行代码)中的参数
5、接下来是,最后一行代码中的title和button1
选择工具-->编译脚本
生成可执行文件如下:
具体代码如下:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
/**
* @author rongrong
* 上传文件演示案例
*/
public class TestUpload {
WebDriver driver;
@BeforeClass
public void beforeClass() {
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void testUpload() {
driver.get("file:///C:/Users/Administrator/Desktop/index.html");
driver.manage().window().maximize();
//选择文件
driver.findElement(By.id("upload")).click();
try {
Runtime.getRuntime().exec("upload.exe");
} catch (IOException e) {
e.printStackTrace();
}
}
@AfterClass
public void afterClass() {
driver.quit();
}
}
效果如下:
到此使用自动化调用autolt上传文件的案例演示结束,可能很多同学会纠结autolt语法不会写啥的,大可不必纠结,基本写完是一劳永逸的,不会在维护了,更多autolt的用法,有兴趣的同学可以自行去官网查看了解。