文件上传__方法汇总__Python

转:https://www.cnblogs.com/VseYoung/p/selenium_upload_python.html

selenium实现文件上传方法汇总(AutoIt、win32GUI、sengkeys)---基于python

在使用selenium进行UI自动化测试时,经常会遇到一个关于本地文件上传的问题,解决此问题一般分两种情况:

1. 元素标签为input

2.非input型上传

下面我们分别对着两种情况进行实例分析

(一)元素标签为input

此种情况处理比较简单,标签为input的上传,可以直接通过send_keys("本地文件路径")实现

举例:(以百度网盘为例)

# coding:utf-8
from selenium import webdriver
from time import sleep
#声明配置文件路径,在路径前加r标识后面跟的路径原意输出,如果不加r需要对路径中的斜杠进行转义
profile_directory=r"C:\Users\55348\AppData\Roaming\Mozilla\Firefox\Profiles\tqc0968l.default"
#加载配置文件
profile=webdriver.FirefoxProfile(profile_directory)
#启动浏览器配置
driver=webdriver.Firefox(profile)
#打开url
driver.get("http://pan.baidu.com")
#隐式等待
driver.implicitly_wait(10)
#点击上传,由于上传按钮是input属性的,所以可以直接通过send_keys
driver.find_element_by_id("h5Input0").send_keys(r"C:\Users\55348\Desktop\03913f358d9be352bd125ae7087dd0d6.apk")
sleep(10)
#判断是否上传成功
new=driver.find_elements_by_xpath("//*[@title='03913f358d9be352bd125ae7087dd0d6.apk' and @class='xj9QOe']")
if len(new)==1:
    print "upload apk ok"
else:
    print "upload apk failed"
driver.quit()

(二)非input情况

此种情况处理比较复杂 ,有三种处理方式:①使用 SendKeys第三方库     ②使用AutoIt第三方工具  ③使用win32 GUI工具

  1.1 使用SendKeys第三方库

  首先进行SendKeys第三方库

  pip install SendKeys

如果出现如下提示:文件上传__方法汇总__Python就多试几次。

如果出现如下提示:文件上传__方法汇总__Python,这种情况,可以根据提示Get it from http://aka.ms/vcpython27

即登录此地址下载C++,下载完成后傻瓜式安装即可。

  其次,在第三方库安装完成后,即可进行上传的动作,具体如下:

# coding:utf-8
from selenium import webdriver
from time import sleep
import SendKeys
from selenium.webdriver.common.keys import Keys
#声明配置文件路径,在路径前加r标识后面跟的路径原意输出,如果不加r需要对路径中的斜杠进行转义
profile_directory=r"C:\Users\55348\AppData\Roaming\Mozilla\Firefox\Profiles\tqc0968l.default"
#加载配置文件
profile=webdriver.FirefoxProfile(profile_directory)
#启动浏览器配置
driver=webdriver.Firefox(profile)
#打开url
driver.get("http://pan.baidu.com")
#隐式等待
driver.implicitly_wait(10)
#仍以百度网盘为例,本次通过点击上传按钮,进行上传文件选择
driver.find_element_by_id("h5Input0").click()
SendKeys.SendKeys(r"C:\Users\55348\Desktop\03913f358d9be352bd125ae7087dd0d6.apk")
sleep(2)
SendKeys.SendKeys("{ENTER}")   #enter键
sleep(2)
SendKeys.SendKeys("{ENTER}")
sleep(5)
#判断是否上传成功
new=driver.find_elements_by_xpath("//*[@title='03913f358d9be352bd125ae7087dd0d6.apk' and @class='xj9QOe']")
if len(new)==1:
    print "upload apk ok"
else:
    print "upload apk failed"
driver.quit()

1.2 使用AutoIt工具

  下面文章摘录于http://blog.csdn.net/huilan_same/article/details/52208363

  1.3 使用Win32 GUI

  下面文章摘录于http://blog.csdn.net/huilan_same/article/details/52439546

备注:

  多文件的上传,可以将文件路径加入到list中,然后通过for循环读取并上传

  upload_directory=[]

  upload_directory.append[r"c:\1.txt"]

  upload_directory.append[r"c:\2.txt"]

  upload_directory.append[r"c:\3.txt"]

  for file in upload_directory: