一、文件上传
1.1 上传文件框的TagName为input形式
- 首先定位上传按钮
- 发送要上传的文件
driver.findElement(By.id("XX")).sendKeys("D:\20.jpg");
1.2 上传文件框不是input形式------使用AutoIT
- autoIT3工具介绍:AutoIT是一个类似脚本语言的软件,利用此软件我们可以方便的实现模拟键盘、鼠标、窗口等操作,实现自动化。利用AutoIT编写合适的脚本,然后将脚本编译成可执行文件,在自动化实现时,直接调用此脚本实现文件上传。下载地址
常用的三个组件:
- AutoIT Window Info(x64) :用来定位
- SciTE Script Editor :用来写脚本
- Compile Script to .exe(x64):用来转换成exe
ControlFocus("选择要上载的文件,通过: pcistest.zsins.com","","Edit1") ControlSetText("选择要上载的文件,通过: pcistest.zsins.com","","Edit1","""C:UsersPublicPicturesSample PicturesLighthouse.jpg""""C:UsersPublicPicturesSample PicturesChrysanthemum.jpg""") ControlClick("选择要上载的文件,通过: pcistest.zsins.com","","Button2") ControlClick("选择要上载的文件,通过: pcistest.zsins.com","","Button2")
测试是否成功的方法:
在浏览器中测试:
- 点击上传文件按钮后,弹出选择文件框,运行脚本时,要保证此窗口打开状态,在SciTE Script Editor中点击Tools的GO,即可运行成功。如图
1.3 上传文件框不是input形式------用robot类
//第三种方法,用robot类(jdk自带)控制模拟键盘操作
Thread.sleep(1000); String path = "D:\image\QQ图片2.jpg"; //图片或文件的路径 StringSelection stringSelection = new StringSelection(path); //指定图片的路径,使用相对路径 Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(stringSelection, null); //把图片路径复制粘贴到剪切板 Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_ENTER); //按下Enter键 robot.keyRelease(KeyEvent.VK_ENTER); //释放Enter键 robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_V); //按下Ctrl+V robot.keyRelease(KeyEvent.VK_CONTROL); robot.keyRelease(KeyEvent.VK_V); //释放Ctrl+V robot.keyPress(KeyEvent.VK_ENTER); //再次点击Enter键 robot.keyRelease(KeyEvent.VK_ENTER); //再次释放Enter键 Thread.sleep(5000);