zoukankan      html  css  js  c++  java
  • WebDriver高阶API(2)

    WebDriver高阶API(2)

    5、更改页面对象属性值 (使用JS修改)

    #encoding=utf-8
    import unittest
    from selenium import webdriver
    
    def addAttribute(driver,elementObj,attributeName,value):
        #封装向页面标签中添加新属性的方法
        #调用JavaScript代码给页面标签添加新属性,arguments[0]-arguments[2]分别会用后面的
        #element、attributeName和value参数值进行替换,并执行该Javascript代码
        #添加新属性的JavaScript代码语法为:element.attributeName = value
        #比如 input.name = 'test'
        # 下面arguments[0] 为elementObj,s%为attributeName,arguments[1] 为value
        driver.execute_script("arguments[0].%s=arguments[1]" % attributeName,elementObj,value)
    
    def setAttribute(driver,elementObj,attributeName,value):
        #封闭设置页面对象的属性值的方法
        # 调用JavaScript代码修改页面元素的属性值,arguments[0]-arguments[2]分别会用后面的
        # element、attributeName和value参数值进行替换,并执行该Javascript代码
        driver.execute_script("arguments[0].setAttribute(arguments[1],arguments[2])", elementObj,attributeName,value)
    
    def getAttribute(elementObj,attributeName):
        #封装获取页面对象的属性值的方法
        return elementObj.get_attribute(attributeName)
    
    def removeAttribute(driver,elementObj,attributeName):
        #封装删除页面元素属性的方法
        # 调用JavaScript代码删除页面元素的指定的属性,arguments[0]-arguments[2]分别会用后面的
        # element、attributeName和value参数值进行替换,并执行该Javascript代码
        driver.execute_script("arguments[0].removeAttribute(arguments[1])", elementObj,attributeName)
    
    class TestDemo(unittest.TestCase):
    
        def setUp(self):
            #启动浏览器
            self.driver = webdriver.Ie(executable_path = "D:\IEDriverServer")
    
        def test_dataPicker(self):
            url = "http://127.0.0.1:8080/operate_attribute.html"
            #访问自定义网页
            self.driver.get(url)
            #找到页面上标签名为input页面元素
            input_element = self.driver.find_element_by_xpath("//input")
            #向页面文本框input标签中添加新属性name = "search"
            addAttribute(self.driver,input_element,"name","search")
            #添加新属性后,查看一下新添加的属性
            print u"添加的析属性值%s='%s'" % ("name",getAttribute(input_element,"name"))
    
            #查看修改前文本框input标签的value属性值
            print u"更改文本框中的内容前的内容:",getAttribute(input_element,"name")
            #更改input页面元素的value属性值为“这是更改后的文字内容”
            setAttribute(self.driver,input_element,"value",u"这是修改后的文字内容")
            #更改input页面元素的value属性后,再次查看其value属性值
            print u"更改文本框中内容后的内容:",getAttribute(input_element,"value")
    
            #查看修改前文本杠input页面元素中的size属性值
            print u"更改前文本框标签的size属性值:",getAttribute(input_element,"size")
            #更改input页面元素的size属性值为“20”
            setAttribute(self.driver,input_element,"size",20)
            #更改input页面元素的size的属性值后,再次查看其size属性值
            print u"更改后文本框标签中的size属性值:",getAttribute(input_element,"size")
    
            #查看删除input页面元素value属性前的value属性值
            print u"文本框value属性值:",getAttribute(input_element,"value")
            #删除文本框的value属性
            removeAttribute(self.driver,input_element,"value")
            #删除文本框的value属性后,再次查看value属性值
            print u"删除value属性值后value属性值:",getAttribute(input_element,"value")
    
        def tearDown(self):
            self.driver.quit()
    
    if __name__ == "__main__":
        unittest.main()

    6、自动下载文件

    电脑上没有Firefox浏览器,本段代码未执行

    #encoding=utf-8
    from selenium import webdriver
    import unittest,time
    
    class TestDemo(unittest.TestCase):
    
        def setUp(self):
            #创建一个FirefoxProfile实例,用于存放甜自定义配置
            profile = webdriver.FirefoxProfile()
            #指定下载路径,默认只会自动创建一级目录,如果指定了多级不存在的目录,将会下载到默认路径
            profile.set_preference("browser.download.dir","D:\test")
            #将browser.download.folderList设置为2,表示将文件下载到指定路径
            #设置成2表示使用自定义下载路径;设置成0表示下载到桌面;设置成1表示下载到默认路径
            profile.set_preference("browser.download.folderList",2)
            #browser.helperApps.alwaysAsk.force对于未知的MIME类型文件会弹出窗口让用户处理,默认为True,
            #设置为False表示不会记录打开 未知MIME类型文件的方式
            profile.set_preference("browser.helperApps.alwaysAsk.force",False)
            #在开始下载时是否显示下载管理器
            profile.set_preference("browser.download.manager.showWhenStarting",False)
            #设定为False会把下载框进行隐藏
            profile.set_preference("browser.download.manager.useWindow",False)
            #默认值为True,设定为False表示不获取焦点
            profile.set_preference("browser.download.manager.focusWhenStarting",False)
            #下载.exe文件弹出警告,默认值为True,设定为False则不会弹出警告框
            profile.set_preference("browser.download.manager.alertOnEXEOpen",False)
            #browser.helperApps.neverAsk.openFile表示直接打开下载文件,不显示确认框
            #默认值为空字符串,下行代码设定了多种文件的MIME类型,例如 application/exe,表示.exe类型的文件
            #application/excel表示Excel类型的文件
            profile.set_preference("browser.helperApps.neverAsk.openFile","application/pdf")
            #对所给出文件类型不再弹出提示框进行询问,直接保存到本地磁盘
            profile.set_preference("browser.helperApps.neverAsk.saveToDisk","application/zip,application/octet-stream")
            #browser.download.manager.showAlertOnComplete设定下载文件结束后是否显示下载完成提示框,
            #默认为True,设定为False表示下载完成后不显示下载完成 提示框
            profile.set_preference("browser.download.manager.showAlertOnComplete",False)
            #browser.download.manager.closeWhenDone设定下载结束后是否自动关闭下载框,默认值为true,
            #设定为False表示不关闭下载管理器
            profile.set_preference("browser.download.manager.closeWhenDone",False)
            #启动浏览器,通过firefox_profile参数将自动配置添加到FirefoxProfile对象中
            self.driver = webdriver.Firefox(executable_path="D:\geckodriver",firefox_profile = profile)
    
        def test_downloadFile(self):
            #访问WebDriver驱动FireFox的驱动文件下载地址
            url1 = "https://github.com/mozilla/geckodriver//releases"
            self.driver.get(url1)
            #选择下载ZIP类型文件,使用application/zip指代此类型文件
            self.driver.find_element_by_xpath("//span[test()='geckodriver-v0.24.0-win32.zip']").click()
            #等待加载下载文件
            time.sleep(10)
    
            #访问Python2.7.12文件下载页面,下载扩展名为msi的文件
            #使用application/octet-stream来指明此类文件类型
            url2 = "https://www.python.org/downloads/release/python-2712/"
            self.driver.get(url2)
            #找到Python2.7.12文件下载页面中链接文字为“Windows x86 - 64 MSI installer”
            #的链接页面元素,单击进行无人工干预的下载Python2.7.12解释器文件
            self.driver.find_element_by_link_text("Windows x86-64 MSI installer").click()
            #等待文件下载完成,根据各自的网络宽带情况设定等待相应的时间
            time.sleep(100)
    
        def tearDown(self):
            self.driver.quit()
    
    if __name__ == "__main__":
        unittest.main()

    7、上传文件
    1)、使用send_keys

    #encoding=utf-8
    import unittest,time
    import traceback
    from selenium import webdriver
    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.Ie(executable_path="D:\IEDriverServer")
    
        def test_uploadFileBySendKeys(self):
            url = "http://127.0.0.1:8080/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")
                #在文件上传框的路径框里输入要上传的文件路径 "D:\test\test.txt"
                fileBox.send_keys("D:\test\test.txt")
                #暂停查看上传的文件
                time.sleep(3)
                #找到页面上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()
  • 相关阅读:
    LVS基于DR模式负载均衡的配置
    Linux源码安装mysql 5.6.12 (cmake编译)
    HOSt ip is not allowed to connect to this MySql server
    zoj 3229 Shoot the Bullet(无源汇上下界最大流)
    hdu 3987 Harry Potter and the Forbidden Forest 求割边最少的最小割
    poj 2391 Ombrophobic Bovines(最大流+floyd+二分)
    URAL 1430 Crime and Punishment
    hdu 2048 神、上帝以及老天爷(错排)
    hdu 3367 Pseudoforest(最大生成树)
    FOJ 1683 纪念SlingShot(矩阵快速幂)
  • 原文地址:https://www.cnblogs.com/test-chen/p/10595211.html
Copyright © 2011-2022 走看看