Python selenium 文件自动下载 (自动下载器)

1.

Firefox 文件下载

对于Firefox,需要我们设置其Profile:

  • browser.download.dir:指定下载路径
  • browser.download.folderList:设置成 2 表示使用自定义下载路径;设置成 0 表示下载到桌面;设置成 1 表示下载到默认路径
  • browser.download.manager.showWhenStarting:在开始下载时是否显示下载管理器
  • browser.helperApps.neverAsk.saveToDisk:对所给出文件类型不再弹出框进行询问

2.实例。

需求:公司里面总是需要在OSS,根据OSS num下载相应的文件。

一共写了三部分:autoDownload.py,getUserInfo.py,userInfo.xlsx

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import xlrd

class XlUserInfo(object):
    def __init__(self,path=‘‘):
        self.path = path
        self.xl = xlrd.open_workbook(self.path)

    def get_sheet_info(self):
        all_info = []
        info0 = []
        info1 = []
        for row in range(0,self.sheet.nrows):
            info = self.sheet.row_values(row)
            info0.append(info[0])
            info1.append(info[1])
        temp = zip(info0,info1)
        all_info.append(dict(temp))
        return all_info.pop(0)

    def get_sheetinfo_by_name(self,name):
        self.name = name
        self.sheet = self.xl.sheet_by_name(self.name)
        return self.get_sheet_info()

if __name__ == ‘__main__‘:
    xl = XlUserInfo(‘userInfo.xlsx‘)
    userinfo = xl.get_sheetinfo_by_name(‘userInfo‘)
    webinfo = xl.get_sheetinfo_by_name(‘WebEle‘)
    print(userinfo)
    print(webinfo)

主要用来从userInfo.xlsx中读取用户信息,web的元素。

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

from selenium import webdriver
from getUserInfo import XlUserInfo
import threading

class AutoDownload(object):
    def __init__(self,file_type,args, args2):
        self.file_type = file_type
        self.args = args
        self.args2 = args2

    def openBrower(self):
        self.profile = webdriver.FirefoxProfile()
        self.profile.accept_untrusted_certs = True
        if self.args2[‘downloadpath‘] is None:
            self.profile.set_preference(‘browser.download.dir‘, ‘c:\\‘)
        else:
            self.profile.set_preference(‘browser.download.dir‘, self.args2[‘downloadpath‘])
            print(self.args2[‘downloadpath‘])
        self.profile.set_preference(‘browser.download.folderList‘, 2)
        self.profile.set_preference(‘browser.download.manager.showWhenStarting‘, False)
        if self.file_type == ‘xml‘:
            self.profile.set_preference(‘browser.helperApps.neverAsk.saveToDisk‘, ‘application/xml‘)
        elif self.file_type == ‘uxz‘:
            self.profile.set_preference(‘browser.helperApps.neverAsk.saveToDisk‘, ‘application/xml‘)
        elif self.file_type == ‘txt‘:
            self.profile.set_preference(‘browser.helperApps.neverAsk.saveToDisk‘, ‘text/plain‘)
        else:
            self.profile.set_preference(‘browser.helperApps.neverAsk.saveToDisk‘, ‘text/plain‘)
        #3,6 xml,tml file
        # profile.set_preference(‘browser.helperApps.neverAsk.saveToDisk‘, ‘application/xml‘)
        #2,4 txt,chg file
        # profile.set_preference(‘browser.helperApps.neverAsk.saveToDisk‘, ‘text/plain‘)
        self.driver = webdriver.Firefox(firefox_profile=self.profile)
        self.driver.implicitly_wait(30)
        return self.driver

    def openUrl(self):
        try:
            self.driver.get(self.args2[‘url‘])
            self.driver.maximize_window()
        except:
            print("Failed to get {}".format(self.args2[‘url‘]))
        return self.driver

    def login(self):
        ‘‘‘
        user_name
        pwd_name
        logIn_name
        ‘‘‘
        self.driver.find_element_by_name(self.args[‘user_name‘]).send_keys(self.args2[‘uname‘])
        if isinstance(self.args2[‘pwd‘],float):
            self.driver.find_element_by_name(self.args[‘pwd_name‘]).send_keys(int(self.args2[‘pwd‘]))
        else:
            self.driver.find_element_by_name(self.args[‘pwd_name‘]).send_keys(self.args2[‘pwd‘])
        self.driver.find_element_by_name(self.args[‘logIn_name‘]).click()
        self.driver.implicitly_wait(10)
        return self.driver

    def download(self):
        self.driver.implicitly_wait(15)
        self.driver.find_element_by_link_text(self.args[‘Search_Forms_text‘]).click()
        self.driver.implicitly_wait(30)
        self.driver.find_element_by_id(self.args[‘OSS_Num_type_id‘]).send_keys(int(self.args2[‘OSS_num‘]))
        self.driver.find_element_by_id(self.args[‘Search_button_id‘]).click()
        self.driver.implicitly_wait(10)
        self.driver.find_element_by_link_text(str(int(self.args2[‘OSS_num‘]))).click()
        self.driver.implicitly_wait(20)
        # Attachments_text
        self.driver.find_element_by_link_text(self.args[‘Attachments_text‘]).click()
        self.driver.implicitly_wait(10)

        if self.file_type == ‘xml‘:
            self.driver.find_element_by_xpath(‘//table[4]//tr[3]/td[1]/a‘).click()
            self.driver.implicitly_wait(30)
            self.driver.find_element_by_xpath(‘//table[4]//tr[6]/td[1]/a‘).click()
        elif self.file_type == ‘uxz‘:
            self.driver.find_element_by_xpath(‘//table[4]//tr[5]/td[1]/a‘).click()
        elif self.file_type == ‘txt‘:
            self.driver.find_element_by_xpath(‘//table[4]//tr[2]/td[1]/a‘).click()
            # driver.find_element_by_xpath(‘//table[4]//tr[6]/td[1]/a‘).click()
            self.driver.implicitly_wait(30)
            self.driver.find_element_by_xpath(‘//table[4]//tr[4]/td[1]/a‘).click()
        else:
            self.driver.quit()

    def quit(self):
        self.driver.quit()

    def Run(self):
        self.openBrower()
        self.openUrl()
        self.login()
        self.download()
        self.quit()

if __name__ == ‘__main__‘:
    xl = XlUserInfo(‘userInfo.xlsx‘)
    userinfo = xl.get_sheetinfo_by_name(‘userInfo‘)
    webinfo = xl.get_sheetinfo_by_name(‘WebEle‘)
    print(userinfo)
    print(webinfo)
    down_txt = AutoDownload(‘txt‘,webinfo,userinfo)
    down_xml = AutoDownload(‘xml‘,webinfo,userinfo)

    threads = []
    t1 = threading.Thread(target=down_txt.Run)
    t2 = threading.Thread(target=down_xml.Run)
    threads.append(t1)
    threads.append(t2)

    for t in threads:
        t.start()
    for i in threads:
        i.join()

时间: 2024-08-30 17:03:24

Python selenium 文件自动下载 (自动下载器)的相关文章

Python Selenium 文件上传(二)

今天补充一种文件上传的方法 主要是因为工作中使用SendKeys方法不稳定,具体方法见: Python Selenium 文件上传(一) 这种方法直接通过命令行执行脚本时没有问题,可以成功上传,但是如果通过saltstack 远程控制执行时,SendKeys就定位不到窗口了. 所以采用这种新的方式来实现文件上传功能,并完美的解决了这个问题. 具体操作步骤如下: 1.下载工具 AutoIt及使用 AutoIt目前最新是v3版本,这是一个使用类似BASIC脚本语言的免费软件,它设计用于Windows

Python Selenium 文件上传(一)

昨天写了Web 文件下载的ui自动化,下载之后,今天就要写web 文件上传的功能了. 当然从折腾了俩小时才上传成功.下面写一下自己操作的步骤 首先网上说的有很多方法 如 input 标签的最好做了,直接定位到元素,然后再sendKeys("value")即可 <input id="file_name" class="text-1 w255" type="text" readonly="" value=

python+selenium实现163邮箱自动登陆

让我们先来预览一下代码运行效果吧: 首先分析163邮箱登陆页面的网页结构(按F12或单击鼠标右键选择审查元素) 1.定位到登陆框(注意登录框是一个iframe,如果不定位到iframe的话是无法找到之后的邮箱地址框和密码输入框的) 2.定位到邮箱地址框(name='email') 3.定位到密码输入框(name='password') 4.定位到登陆按钮(id='dologin') 5.分析完毕,现在就可以写代码实现163邮箱的自动登陆啦(附有代码的详细解析!) #coding:utf-8 fr

python+selenium+webdriver+BeautifulSoup实现自动登录

from selenium import webdriver import time from bs4 import BeautifulSoup url = "http://www.hsbkos.com/" soup = BeautifulSoup() soup.findAll('div',{'class':'objbox'}) driver = webdriver.Chrome() time.sleep(1) driver.get(url) time.sleep(1) driver.

python+selenium+unittest测试框架2-装饰器@classmethod

装饰器@classmethod 一.装饰器@classmethod 多个用例可能需要多次打开浏览器,装饰器@classmethod只打开一次浏览器.classmethod是python里的类方法,@是修饰符号. 1.setUpClass(): @classmethod def setUpClass(cls): 2.tearDownClass(): @classmethod def tearDownClass(cls): 示例: from selenium import webdriver fro

python+selenium文件上传

1.input标签类元素文件上传 先定位到文件上传元素id,再使用方法send_keys(文件路径) 2.非input标签 备注:非input标签的文件上传,就不适用于此方法了,需要借助autoit工具或者SendKeys第三方库.

Python+Selenium搭建UI自动化测试框架

Python语言是非常强大的编程语言,很多时候也拿来当脚本语言用. Selenium是web应用测试工具,支持Java.Python等多种语言脚本,支持Chrome.Firefox等多种主流浏览器.主要实现的就是模拟人使用web应用,自动的打开浏览器.打开应用.进入应用进行各种模拟业务操作等等. 接下来,一步一步带领大家实现下Python+Selenium实现使用脚本自动发微博的功能. 1.Python安装 一般Linux系统自带了Python,Windows系统可以参考本人之前文章 [Pyth

Python WebDriver 文件上传

昨天写了Web 文件下载的ui自动化,下载之后,今天就要写web 文件上传的功能了. 当然从折腾了俩小时才上传成功.下面写一下自己操作的步骤 首先网上说的有很多方法 如 input 标签的最好做了,直接定位到元素,然后再sendKeys("value")即可 <input id="file_name" class="text-1 w255" type="text" readonly="" value=

自动更新开奖数据的excel文件,供大家下载

自动更新开奖数据的excel文件,供大家下载 2010-03-14 20:22 228492人阅读打印来源:乐彩网 作者:eren 很多人拥有自制excel电子表格,常要更新最基本的开奖信息.如有多期未更新,则费时更多.乐彩网为大家提供八种彩票的自动更新文件,供下载.您只需点击更新按钮,就能得到最及时全面的开奖信息,省时省力. 2011年10月12日修改说明:已更新全部开奖数据.福彩3Dexcel文件中,因描述更新范围的高度小了,导致更新后,最下面内容会右移.如此文件单独存在,请直接下载.如已将