方法一:使用webdriver的send_keys方法上传文件,代码如下:

#encoding=utf-8
from selenium import webdriver
import unittest
import time
import traceback
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException class TestDemo(unittest.TestCase): def setUp(self):
# 启动Chrome浏览器
self.driver = webdriver.Ie(executable_path = "e:\\IEDriverServer") def test_uploadFileBySendKeys(self):
url = "http://127.0.0.1/test_upload_file.html"
# 访问自定义网页
self.driver.get(url)
try:
# 创建一个显示等待对象
wait = WebDriverWait(self.driver, 10, 0.2)
# 显示等待判断被测试页面上的上传文件按钮是否处于可被点击状态
wait.until(EC.element_to_be_clickable((By.ID, 'file')))
except TimeoutException, e:
# 捕获TimeoutException异常
print traceback.print_exc()
except NoSuchElementException, e:
# 捕获NoSuchElementException异常
print traceback.print_exc()
except Exception, e:
# 捕获其他异常
print traceback.print_exc()
else:
# 查找页面上ID属性值为“file”的文件上传框
fileBox = self.driver.find_element_by_id("file")
# 在文件上传框的路径框里输入要上传的文件路径“c:\\test.txt”
fileBox.send_keys("c:\\test.txt")
# 暂停查看上传的文件
time.sleep(4)
# 找到页面上ID属性值为“filesubmit”的文件提交按钮对象
fileSubmitButton = self.driver.find_element_by_id("filesubmit")
# 单击提交按钮,完成文件上传操作
fileSubmitButton.click()
# 因为文件上传需要时间,所以这里可以添加显示等待场景,
# 判断文件上传成功后,页面是否跳转到文件上传成功的页面。
# 通过EC.title_is()方法判断跳转后的页面的Title
# 值是否符合期望,如果匹配将继续执行后续代码
#wait.until(EC.title_is(u"文件上传成功")) def tearDown(self):
# 退出IE浏览器
self.driver.quit() if __name__ == '__main__':
unittest.main()

方法二:模拟键盘操作,实现上传文件,代码如下:

#encoding=utf-8
from selenium import webdriver
import unittest
import time
import traceback
import win32clipboard as w
import win32api
import win32con
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException # 用于设置剪切板内容
def setText(aString):
w.OpenClipboard()
w.EmptyClipboard()
w.SetClipboardData(win32con.CF_UNICODETEXT, aString)
w.CloseClipboard() # 键盘按键映射字典
VK_CODE = {
'enter':0x0D,
'ctrl':0x11,
'v':0x56} # 键盘键按下
def keyDown(keyName):
win32api.keybd_event(VK_CODE[keyName], 0, 0, 0)
# 键盘键抬起
def keyUp(keyName):
win32api.keybd_event(VK_CODE[keyName], 0, win32con.KEYEVENTF_KEYUP, 0) class TestDemo(unittest.TestCase): def setUp(self):
# 启动Chrome浏览器
self.driver = webdriver.Ie(executable_path = "e:\\IEDriverServer") def test_uploadFileByKeyboard(self):
url = "http://127.0.0.1/test_upload_file.html"
# 访问自定义网页
self.driver.get(url)
try:
# 创建一个显示等待对象
wait = WebDriverWait(self.driver, 10, 0.2)
# 显示等待判断被测试页面上的上传文件按钮是否处于可被点击状态
wait.until(EC.element_to_be_clickable((By.ID, 'file')))
except TimeoutException, e:
# 捕获TimeoutException异常
print traceback.print_exc()
except NoSuchElementException, e:
# 捕获NoSuchElementException异常
print traceback.print_exc()
except Exception, e:
# 捕获其他异常
print traceback.print_exc()
else:
# 将即将要上传的文件名及路径设置到剪切板中
setText(u"c:\\test.txt")
# 查找页面上ID属性值为“file”的文件上传框,
# 并点击调出选择文件上传框
self.driver.find_element_by_id("file").click()
time.sleep(2)
# 模拟键盘按下ctrl + v组合键
keyDown("ctrl")
keyDown("v")
# 模拟键盘释放Ctrl + v组合键
keyUp("v")
keyUp("ctrl")
time.sleep(1)
# 模拟键盘按下回车键
keyDown("enter")
# 模拟键盘释放回车键
keyUp("enter")
# 暂停查看上传的文件
time.sleep(2)
# 找到页面上ID属性值为“filesubmit”的文件提交按钮对象
fileSubmitButton = self.driver.find_element_by_id("filesubmit")
# 单击提交按钮,完成文件上传操作
fileSubmitButton.click()
# 因为文件上传需要时间,所以这里可以添加显示等待场景,
# 判断文件上传成功后,页面是否跳转到文件上传成功的页面。
# 通过EC.title_is()方法判断跳转后的页面的Title
# 值是否符合期望,如果匹配将继续执行后续代码
#wait.until(EC.title_is(u"文件上传成功")) def tearDown(self):
# 退出IE浏览器
self.driver.quit() if __name__ == '__main__':
unittest.main()

方法三:使用第三方工具AutoIt上传文件

使用第三方工具AutoIt可以操作一些WebDriver无法操作的文件上传对象。需要先下载并按照此工具,才能调用如下代码实现上传:

下载链接: https://pan.baidu.com/s/12aBBhOOTmyQpH9hukt0XGA 密码: fcdk

代码:

#encoding=utf-8
from selenium import webdriver
import unittest
import time, os
import traceback
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException class TestDemo(unittest.TestCase): def setUp(self):
# 启动Chrome浏览器
self.driver = webdriver.Ie(executable_path = "e:\\IEDriverServer") def test_uploadFileByAutoIt(self):
url = "http://127.0.0.1/test_upload_file.html"
# 访问自定义网页
self.driver.get(url)
try:
# 创建一个显示等待对象
wait = WebDriverWait(self.driver, 10, 0.2)
# 显示等待判断被测试页面上的上传文件按钮是否处于可被点击状态
wait.until(EC.element_to_be_clickable((By.ID, 'file')))
except TimeoutException, e:
# 捕获TimeoutException异常
print traceback.print_exc()
except NoSuchElementException, e:
# 捕获NoSuchElementException异常
print traceback.print_exc()
except Exception, e:
# 捕获其他异常
print traceback.print_exc()
else:
# 查找页面上ID属性值为“file”的文件上传框,
# 并点击调出选择文件上传框
self.driver.find_element_by_id("file").click()
# 通过Python提供的os模块的system方法执行生成的test.exe文件
os.system("E:\\test.exe")
# 由于AutoIt脚本转换后的可执行文件test.exe可能执行速度比较慢,
# 这里等待5秒,以确保test.exe脚本执行成功
time.sleep(5)
# 找到页面上ID属性值为“filesubmit”的文件提交按钮对象
fileSubmitButton = self.driver.find_element_by_id("filesubmit")
# 单击提交按钮,完成文件上传操作
fileSubmitButton.click()
# 因为文件上传需要时间,所以这里可以添加显示等待场景,
# 判断文件上传成功后,页面是否跳转到文件上传成功的页面。
# 通过EC.title_is()方法判断跳转后的页面的Title
# 值是否符合期望,如果匹配将继续执行后续代码
#wait.until(EC.title_is(u"文件上传成功"))
time.sleep(2)
def tearDown(self):
# 退出IE浏览器
self.driver.quit() if __name__ == '__main__':
unittest.main()

webdriver高级应用- 无人工干预地自动上传附件的更多相关文章

  1. webdriver高级应用- 无人工干预地自动下载某个文件

    在网页上下载文件时,通常需要人为设定下载文件并选择保持路径,这样就无法实现完全自动的下载过程.下面实现基于firefox浏览器的全自动化文件下载操作: #encoding=utf-8 from sel ...

  2. webdriver高级应用 -无人干预地自动上传文件

    本节主要介绍通过程序代码无人干预地上传文件附件,并进行提交操作. 1.使用send_keys方法上传文件 #!/usr/bin/env python # -*- coding: utf-8 -*- # ...

  3. selenium3 无人工干预地自动下载某个文件

    一:主要内容 下载效果展示 代码内容展示 saveToDisk不生效说明,即文件没有下载下来解决办法 二:展示效果 1.下载效果展示 用selenium3无人工干预的自动下载该文件到指定路径下,如:D ...

  4. Selenium WebDriver高级用法

    Selenium GitHub地址 选择合适的WebDrvier WebDriver是一个接口,它有几种实现,分别是HtmlUnitDrvier.FirefoxDriver.InternetExplo ...

  5. Selenium WebDriver高级应用

    WebDriver高级应用 public class Demo4 { WebDriver driver; // @BeforeMethod:在每个测试方法开始运行前执行 @BeforeMethod p ...

  6. webdriver高级应用(2) - 滚动条操作

    webdriver高级应用(2) - 滚动条操作 #-*- coding:utf-8 -*- from selenium import webdriver import unittest import ...

  7. 用webdriver+phantomjs实现无浏览器的自动化过程

    环境准备 1. 安装python: 2. 安装pip: 3. 通过pip安装selenium: 4. 下载phantomJS的包并解压缩: 1. 若在Windows系统中,将下载的phantomjs文 ...

  8. Selenium webdriver 高级应用

    对于这一段还蛮有感慨的,只想说,代码还是需要自己去敲的. 1. 改变用户代理 import org.junit.AfterClass; import org.junit.BeforeClass; im ...

  9. ajax+FormData+javascript 实现无刷新上传附件

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

随机推荐

  1. 1068 乌龟棋 2010年NOIP全国联赛提高组

    1068 乌龟棋 2010年NOIP全国联赛提高组  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 钻石 Diamond 题解  查看运行结果     题目描述 Descrip ...

  2. ABAP事件的简单用法

    1.1.事件: 用于捕获某类对象状态的改变来触发事件的方法,并进行处理 1.2.定义:可以在类或接口中进行声明 EVENTS|CLASS-EVENTS evt  EXPORTING … VALUE(p ...

  3. Windows下Python多版本共存

    Windows下Python多版本共存 Python数据科学安装Numby,pandas,scipy,matpotlib等(IPython安装pandas) 0.0 因为公司项目,需要Python两个 ...

  4. 【Android】ContentProvider

    转载地址:http://www.cnblogs.com/lqminn/archive/2012/10/16/2725624.html 一.ContentProvider的概念 ContentProvi ...

  5. Oracle listener.ora 设置

  6. 深度探索C++对象模型——关于对象

    引言 以前读<C++ Primer>的时候一直有一种感觉:该书虽然是C++入门书籍,初学者读之却觉晦涩,越往后读越是如此.等到稍加理解后再读该书,顿感醍醐灌顶,茅塞顿开.究其原因,在于原作 ...

  7. Python一个有意思的地方:reduce、map、filter

    今天阅读了关于Python函数式编程的系列文章,地址在这里: http://www.cnblogs.com/huxi/archive/2011/06/24/2089358.html 里面提到了四个内建 ...

  8. SharePoint Online和SharePoint 2016 导出到Excel 表错误

    导出到Excel是一个有用的SharePoint功能.偶尔您可能会遇到该功能无法正常工作的情况.有几个原因可能导致此功能无法正常工作. Problem #1 使用非32位Internet Explor ...

  9. codeforces Gym 100286J Javanese Cryptoanalysis (二染色)

    每一单词相邻两个字母,不能同时为元音或者辅音... 各种姿势都可以过:7个for,dp,黑白染色,dfs,并查集.... 最主要的思路就是相邻字母连边,把元音和辅音看成两个集合,那么有连边的两个字母一 ...

  10. Spark Job调优(Part 2)

    原文链接:https://wongxingjun.github.io/2016/05/11/Spark-Job%E8%B0%83%E4%BC%98-Part-2/ 这篇文章将会完成Part 1中留下的 ...