通过网上资料查询,暂时记录两种文件上传的方法:

测试网址:​​http://www.sahitest.com/demo/php/fileUpload.htm​​​

一、通过send_keys方法(该方法只适用于input标签)

1.查看上传按钮的元素标签为input标签

selenium --上传文件基于python_chrome

2.直接使用以下代码即可:

# _*_ coding=utf-8 _*_
from selenium import webdriver
import os

url = "http://www.sahitest.com/demo/php/fileUpload.htm"
driver = webdriver.Chrome()
driver.get(url)
driver.find_element_by_xpath('//*[@id="file4"]').send_keys("C:\\Users\\saas\\Desktop\\ump.xlsx")

二、通过autoit来处理上传文件问题(适用所有)

​​

2.由于不同的浏览器,获取到的弹窗标题不一样,所以要区分开,通过传参的方式判定,废话少说,直接上autoit的代码:

;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[2] ;第二个参数
;都是从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获取到的
Sleep(1000)
ControlClick($title,"","Button1") ;点击保存或者打开或者上传按钮,此“Button1”使用FinderTool获取到的
Else
Return False
EndIf
EndFunc

3.将上面#2的代码编译为exe文件,以供代码调用

4.通过python代码调用#3编译的exe文件处理上传弹窗,使用什么浏览器就传什么参数

from selenium import webdriver
import os
import time

url = "http://www.sahitest.com/demo/php/fileUpload.htm"
driver = webdriver.Chrome()
driver.get(url)
driver.find_element_by_xpath('//*[@id="file"]').click()
command = "C:\\upload.exe" + " " + "chrome" + " " + "C:\\ump.xlsx"
os.system(command)
time.sleep(3)
driver.close()

由于#2中已经加了等待弹窗出现的时间,所以python中未加等待时间,必要的时候需要加时间等在,来降低脚本的出错率。

​​​​

三、其他方法

1.其余的方法没有去实验,感觉这两种够用了,感兴趣的可以研究下​​​