web自动化之文件上传(转)


背景

在做 Web 自动化时,我们经常会碰到一些场景需要进行文件上传,而文件上传打开的窗口属于 windows 控件,通过 Selenium 是操作不了的,此篇文章给大家介绍几种实现方法。

方法一:sendKeys

前提条件:
文件上传元素是 input 标签,并且 type 为 file 才可以使用此种方法

以我在本地的 fileupload.html 文件为例:




	
	文件上传示例


	


测试代码如下:

ChromeDriver driver = new ChromeDriver();
driver.get("D:\\fileupload.html");
Thread.sleep(2000);
driver.findElement(By.id("fu")).sendKeys("D:\\java_auto\\test.png");

此方法的核心在于元素是 input 类型,可以借由 sendKeys 方法去输入上传文件的路径即可

方法二:AutoIT

针对不是 input 类型的元素,我们可以使用第三方的自动化工具,比如:Auto,对 windows 控件元素进行操作

以下是其官网介绍:

AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys).

翻译过来就是:

AutoIT 是类似于 Basic 脚本语言的免费软件,利用它我们可以实现对 windows 的 GUI 界面进行自动化操作,balabala...

官网地址:https://www.autoitscript.com/site/autoit/

强烈建议先去看官方文档:https://www.autoitscript.com/autoit3/docs/,对工具的使用和脚本编写语法描述的非常详细

step1:下载安装

下载页面在这里:https://www.autoitscript.com/site/autoit/downloads/

点击下载即可,下载完下一步直到安装完毕

安装完毕会有如下几个应用:

其中我们用得到的有:

  • AutoIT Window Info 识别 Windows 元素信息
  • Complie Script to .exe 将 AutoIT 编写的脚本编译成 exe 可执行文件
  • Run Script 运行 AutoIT 脚本
  • SciTE Script Editor 编写 AutoIT 脚本

注意:官方推荐使用 X86 版本,这样兼容性问题会少些

step2:使用 AutoIT

  • 将上传的 Windows 窗口打开
  • 打开 AutoIT Window Info 工具,Finder Tool 下的图标一直按住,选择窗口中要识别的元素(文件名后面的输入框以及打开按钮),分别记录下此时的 Tile、Class 等信息

  • 打开 SciTE Script Editor,开始进行脚本编写(注意元素的定位是由 Class 和 Instance 进行拼接的,如 Class 为 Edit,Instance 为 1,那么定位表达式为 Edit1)

    ;等待“打开”窗口
    WinWaitActive("打开")
    ;休眠2秒
    Sleep(2000)
    ;在输入框中写入上传文件的路径
    ControlSetText("打开", "", "Edit1", "d:\java_auto\test.png")
    ;休眠2秒
    Sleep(2000)
    ;点击打开按钮
    ControlClick("打开", "","Button1");
    
  • 选择工具栏上面的 Tools-Go 先去运行下脚本,试运行 OK 之后将脚本保存,后缀为 au3

  • 选择 Complie Script to .exe 工具把脚本编译为 exe 文件

  • Java 代码本地执行 exe 文件

    ChromeDriver driver = new ChromeDriver();
    driver.get("D:\\fileupload.html");
    Thread.sleep(2000);
    driver.findElement(By.id("fu")).click();
    //Java运行时对象
    Runtime runtime = Runtime.getRuntime();
    try {
        //执行
        runtime.exec("D:\\upload.exe");
    }catch (IOException e){
        e.printStackTrace();
    }
    

    来看看运行效果:


转载来源:

作者:shakebabe
链接:http://testingpai.com/article/1595507303689
来源:测试派