写在前面:
上传文件是每一个自动化测试同窗会遇到,并且能够说是面试必考的问题,标准控件咱们通常用sendkeys()就能完成上传,可是咱们的测试网站的上传控件通常为本身封装的,用传统的上传已经很差用了,也就是说用selenium的APi已经没法完成上传操做了,这时咱们就要借用第三方工具Autolt来完成上传文件的操做。html
准备工做
一、下载autoltjava
官网:https://www.autoitscript.com/site/autoit/downloads/,请自行下载web
也能够百度下载绿色版,免安装,笔者就是绿色版,下面案例都以绿色版进行讲解面试
附百度网盘:连接: https://pan.baidu.com/s/1szmGK7wudsXKkH5xkEOnOQ 提取码: dysb chrome
二、下载后解压到指定目录工具
三、被测网页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>
编写上传脚本
- 找到解压目录,双击AU3TOOL.exe,打开界面是写脚本用的
- 双击Au3Info.exe,打开定位工具界面
-
在文件中输入如下代码:注意括号内的参数 ,下一步中会讲如何获取参数网站
ControlFocus("title1","","Edit1"); WinWait("[CLASS:#32770]","",10); ControlSetText("title1","","Edit1","文件地址"); Sleep(2000); ControlClick("title2","","Button1");
获取上一步中(前3行代码)中的参数ui
- 接下来是,最后一行代码中的title和button1
生成可执行程序
选择工具-->编译脚本spa
生成可执行文件以下:
自动化测试脚本调用upload.exe完成上传
具体代码以下:
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的用法,有兴趣的同窗能够自行去官网查看了解。