Selenium+Python附件上传

在自动化测试过程中,我们会经常遇到附件上传,而附件上传主要分为两种:input型非input型,我们本章就两种不同类型的上传方式讲解:
(1)input型

<input id="txt_userfile" class="file" type="file" value="" name="txt_userfile"> 

针对这种我们的操作方式如下:

# 文件路径,r为防转义字符
driver.find_element_by_name('txt_userfile').send_keys(r"E:\test.jpg") 

(2)非input型

  • 使用SendKeys第三方库

安装方式:pip install SendKeys

# coding:utf-8
from selenium import webdriver
import time
import SendKeys #指定配置文件路径,并加载 profile_directory=r"x" profile=webdriver.FirefoxProfile(profile_directory) driver=webdriver.Firefox(profile) driver.get("") driver.maximize_window() time.sleep(2) ''' 本程序以公司地址为例,你们实验的时候可以用百度网盘、博客园等 ''' driver.find_element_by_id("id").click() #输入文件地址,绝对路径 SendKeys.SendKeys(r"x") time.sleep(2) #输入回车键 SendKeys.SendKeys("{ENTER}") time.sleep(2) #判断文件是否上传成功,在文件路径展示的地方,使用firebug邮件查看位置 new=driver.find_elements_by_xpath("x") if len(new)==1: print "上传成功" else: print "上传失败" 
  • 使用AutoIT
    下载工具 AutoIt官网下载地址
     
    图片1.png

    主要作用:
    • AutoIt Windows Info 用于帮助我们识Windows控件信息。

    • Compile Script to.exe 用于将AutoIt生成 exe 执行文件。

    • Run Script 用于执行AutoIt脚本。

    • SciTE Script Editor 用于编写AutoIt脚本。
      可以参考中文文档

具体用法:
1.首先打开AutoIt Windows Info 工具,鼠标点击Finder Tool(按住左键不松手),鼠标将变成一个小风扇形状的图标,移动到目标控件上;如图:

 
图片2.png

2.通过AutoIt Windows Info 获得以下信息。

窗口的title为“文件上传”,标题的Class为“#32770”。

文件名输入框的class 为“Edit”,Instance为“1” ,ClassnameNN为“Edit1”。

打开按钮的class 为“Button”,Instance为“1” ,所以ClassnameNN为“Button1”。
3.编写脚本(因为IE、Chrome、FireFox文件上传的左上角位置title不一致,所以我们坐下适配)
编写工具:SciTE Script Editor应用程序

; ';'是注释会注释后面的内容
;first make sure the number of arguments passed into the scripts is more than 1
If $CmdLine[0]<2 Then Exit EndIf ;if parmas num <2 ,then break ;$$CmdLine[0] 获取的是命令行参数的总数 ;$CmdLine[1]~$CmdLine[63] 获取的是命令行参数第1到第63位,这个方式最多只能获取63个参数,不过正常情况下是足够用的 ;都是从cmd传入参数 handleUpload($CmdLine[1],$CmdLine[2]) ;定义上传函数,有两个参数,第一个是浏览器名字,第二参数是文件路径 Func handleUpload($browser, $uploadfile) Dim $title ;定义一个title变量 ;根据弹窗的title来判断是什么浏览器 If $browser="ie" Then ; 代表IE浏览器 $title="选择要加载的文件" ElseIf $browser="chrome" Then ; 代表谷歌浏览器 $title="打开" ElseIf $browser="firefox" Then ; 代表火狐浏览器 $title="文件上传" EndIf if WinWait($title,"",4) Then ;等待弹出出现,最大等待时间是4秒 WinActivate($title) ;找到弹出窗口之后,激活当前窗口 ControlSetText($title,"","Edit1",$uploadfile) ;把文件路径放入输入框,此”Edit1“是用FinderTool获取到的 ControlClick($title,"","Button1") ;点击保存或者[图片上传中...(20170928112922.jpg-b2f48a-1515911820298-0)] 打开或者上传按钮,此“Button1”使用FinderTool获取到的 Else Return False EndIf EndFunc 

PS脚本来自lucky_zhang

转换成exe文件:打开autoit安装目录下的应用程序:Compile Script to .exe (x86)或者Compile Script to .exe (x64)

 
图片4.png

在selenium中的调用:

#coding=utf-8
import os
#格式为:EXE位置+浏览器名称+附件位置
path=r'E:\fujianshangchuan.exe firefox E:\20170928112922.jpg' os.popen(path)


作者:路由心定
链接:https://www.jianshu.com/p/a8e4ffddf76f
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自www.cnblogs.com/lansan0701/p/11841236.html
今日推荐