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

本节主要介绍通过程序代码无人干预地上传文件附件,并进行提交操作。

1、使用send_keys方法上传文件

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/2/14 18:48
# @Author  : solo
# @Site    :
# @File    : webdriver_11_7.py
# @Software: PyCharm
 
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):
        #启动浏览器
        self.driver = webdriver.Firefox()
         
    def test_uploadFileBySendKeys(self):
        url = "d:\\uploadFile.html"
        #访问自定义网页
        self.driver.get(url)
        try:
            #创建一个显式等待对象
            wait = WebDriverWait(self.driver,10,0.2)
            #显式等待判断被测试页面上的上传文件按钮是否处于可被单击状态
            wait.until(EC.element_located_to_be_clickable((By.ID,'file')))
        except TimeoutException,e:
            #捕获TimeoutException异常
            print traceback.print_exc()
        except NoSuchElementException,e:
            #捕获NoSuchElement异常
            print traceback.print_exc()
        except Exception,e:
            #捕获其他异常
            print traceback.print_exc()
             
        else:
            #查找页面上ID属性值为‘file’的文件上传框
            fileBox = self.driver.find_element_by_id("file")
            #在文件上传框的路径框里输入要上传的文件路径
            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
            #值是否符合期望,如果匹配将继续执行后续代码
             
            #如果时间了parse_file.jsp页面,并且可以成功调转,
            #可以将下面代码取消注释,断言文件上传成功
            #wait.until(EC.title_is(u"文件上传成功"))
             
             
    def tearDown(self):
        #退出浏览器
        self.driver.quit()
         
if __name__ == "__main__":
    unittest.main()

  

posted @   局长  阅读(358)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示