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


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

    1、使用send_keys方法上传文件

    #!/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()
    

      

  • 相关阅读:
    排列算法问题
    g00 网站说明
    leetcode 401. Binary Watch
    滴滴快车奖励政策,高峰奖励,翻倍奖励,按成交率,指派单数分级(1月7日)
    北京Uber优步司机奖励政策(1月6日)
    滴滴快车奖励政策,高峰奖励,翻倍奖励,按成交率,指派单数分级(1月6日)
    北京Uber优步司机奖励政策(1月5日)
    滴滴快车奖励政策,高峰奖励,翻倍奖励,按成交率,指派单数分级(1月5日)
    全国Uber优步司机奖励政策 (12月28日-1月3日)
    全国Uber优步司机奖励政策 (1月4日-1月10日)
  • 原文地址:https://www.cnblogs.com/aszeno/p/10380761.html
Copyright © 2020-2023  润新知