zoukankan      html  css  js  c++  java
  • Selenium 2自动化测试实战19(下载文件)

    一、下载文件

    webDriver允许设置默认的文件下载路径,也就是说,文件会自动下载并且存放到设置的目录中。下面以火狐浏览器为例,执行文件的下载。

    #downfile.py
    # -*- coding: utf-8 -*-
    
    from selenium import webdriver
    from time import sleep
    
    profile = webdriver.FirefoxProfile()
    profile.set_preference('browser.download.dir', 'd:\')
    profile.set_preference('browser.download.folderList', 2)
    profile.set_preference('browser.download.manager.showWhenStarting', False)
    profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/zip')
    
    driver = webdriver.Firefox(firefox_profile=profile)
    
    driver.get('http://sahitest.com/demo/saveAs.htm')
    driver.find_element_by_xpath('//a[text()="testsaveas.zip"]').click()
    sleep(3)
    driver.quit()
    

    为了让Firefox浏览器能实现文件下载,需要通过FirefoxProfile()对其做一些设置。

    Browser.download.folderList
    设置成0代表下载到浏览器默认下载路径,设置成2则可以保存到指定目录。
    

     

    browser.download.manager.showWhenStarting
    是否显示开始:True为显示,False为不显示
    
    browser.download.dir
    用于指定所下载文件的目录。os.getcwd()函数不需要传递参数,用于返回当前的目录。
    
    browser.helperApps.neverAsk.saveToDisk
    指定要下载页面的Content-type值,“application/zip”为文件的类型
    

      

    HTTPContent-type常用对照表:http://tool.oschina.net/commons

    这些参数的设置可以通过在Firefox浏览器地址栏输入:about:config进行设置,如下图所示

    将所有设置信息在调用WebDriver的Firefox()方法时作为参数传递给浏览器。FireFox浏览器在下载时就根据这些设置信息将文件下载到当前脚本的目录下。

    不同的浏览器设置方法会有所不同。通用的方法还是借助AutoIt来操作Windows控件进行下载。

  • 相关阅读:
    sql查询语句
    java网络编程实现两端聊天
    Thread和Runnable的子类调用
    接口和抽象类
    ObjectOutputStream和ObjectInputStream的简单使用
    HashMap遍历和使用
    InputStreamReader读取文件出现乱码
    Neural Network
    Logistic Regression 逻辑回归
    Linear Regression 线性回归
  • 原文地址:https://www.cnblogs.com/Rita-LJ/p/11698993.html
Copyright © 2011-2022 走看看