文件上传是所有UI自动化测试都要面对的一个头疼问题,因为上传过程中要打开windows系统本地窗口,webdriver没有提供具体的方法。我们要区分出上传按钮的种类,大体上可以分为两种,一种是input框,另外一种就比较复杂,通过js、flash等实现,标签非input。

input标签上传文件

如果带有input标签直接可以用send_keys方法上传文件,首先保存并打开以下HTML。

upload.html

<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>upload_file</title>
<link href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
  <div class="row-fluid">
    <div class="span6 well">
    <h3>upload_file</h3>
      <input type="file" name="file" />
    </div>
  </div>
</body> <script src="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.js"></script>
</html>

markdown 代码实例:

#author:命命 
from selenium import webdriver 
from time import sleep 
driver = webdriver.Chrome() 
driver.maximize_window() 
#打开upload_html 
driver.get("C:\\Users\Administrator\Desktop\\upload.html") 
#上传名字为zhang.jpg的图片 
driver.find_element_by_css_selector("input[type='file']").send_keys("E:\\zhang.jpg") 
sleep(3) 

非input标签上传文件

对于那些不是input框实现的上传怎么办,这种上传千奇百怪,有用a标签的,有用div的,有用button的,有用object的。这里我们使用AutoIt,借助第三方工具,我们去调用其生成的au3或exe文件。

autoIT下载地址: https://www.autoitscript.com/site/autoit/downloads/

安装完成可以在开始菜单栏看见AutoIt目录:

方法 用途
AutoIt Windows Info 用于帮助我们识Windows控件信息
Compile Script to.exe 用于将AutoIt生成 exe 执行文件
Run Script 用于执行AutoIt脚本
SciTE Script Editor 用于编写AutoIt脚本

1.打开upload.html,点击“选择文件”弹出Windows弹框

markdown

2.首先打开AutoIt Windows Info 工具,鼠标点击Finder Tool,鼠标将变成一个小风扇形状的图标,按住鼠标左键拖动到需要识别的控件上。

markdown markdown

3.根据AutoIt Windows Info 所识别到的控件信息打开SciTE Script Editor编辑器,编写脚本。

;ControlFocus("title","text","controlID") Edit1 = Edit instance 1
ControlFocus("打开","","Edit1")

;Wait 10 second for the Upload window to appear
WinWait("[CLASS:#32770]","",10)

;Set the file name text on the Edit field
ControlSetText("打开","","Edit1","E:\zhang.jpg")
Sleep(2000) 

;Click on the Open button 
ControlClick("打开","","Button1")

ControlFocus()方法用于识别Window窗口。WinWait()设置10秒钟用于等待窗口的显示,其用法与WebDriver 所提供的implicitly_wait()类似ControlSetText()用于向“文件名”输入框内输入本地文件的路径。这里的Sleep()方法与Python中time模块提供的Sleep()方法用法一样,不过它是以毫秒为单位,Sleep(2000)表示固定休眠2000毫秒。ControlClick()用于点击上传窗口中的“打开”按钮。

AutoIt的脚本已经写好了,可以通过菜单栏“Tools”-->“Go” (或按键盘F5)来运行一个脚本吧!注意在运行时上传窗口当前处于打开状态。

4.脚本转换为exe程序

脚本运行正常,将其保存为upfile.au3,这里保存的脚本可以通过Compile Script to .exe 工具将其打开运行,但我们的目的是希望这个脚本被Python程序调用,那么就需要将其生成exe程序。

打开Compile Script to.exe工具,将其生成为exe可执行文件。点击“Browse”选择upfile.au3文件,点击“Convert”按钮将其生成为upfile.exe程序 markdown

5.下面就是通过自动化测试脚本调用upfile.exe程序实现上传

#author:命命
from selenium import webdriver
from time import sleep
import os 
driver = webdriver.Chrome() 
driver.maximize_window() 
#打开upload_html 
driver.get("C:\\Users\Administrator\Desktop\\upload.html") 
driver.find_element_by_css_selector("input[type='file']").click() 
sleep(1) 
#上传名字为zhang.jpg的图片 
os.system("E:\\upfile.exe") 
driver.quit()

版权声明:如无特殊说明,文章均为本站原创,转载请注明出处

本文链接:http://zhangyanc.club/subject/article/selenium-upload/

许可协议:署名-非商业性使用 4.0 国际许可协议