python下载网站文件

简介: 场景说明:1、定时从网站下载程序文件;2、定时清理文件,以免占用磁盘空间过大; 程序功能:1、使用urllib2,urllib类从网站抓取数据,并下载到指定路径;2、为避免重复下载,在下载前做数据对比;3、使用多线程,一个实现下载的功能,另一个实现清理功能;4、每24小时执行一次。

场景说明:
1、定时从网站下载程序文件;
2、定时清理文件,以免占用磁盘空间过大;

程序功能:
1、使用urllib2,urllib类从网站抓取数据,并下载到指定路径;
2、为避免重复下载,在下载前做数据对比;
3、使用多线程,一个实现下载的功能,另一个实现清理功能;
4、每24小时执行一次。

import urllib2,urllib
import re
import os,sys
import time
import datetime
import threading

proxy_info={'user':'user', 'password':'xxxxxx' , 'server':'http://xxx:8080'}
url1 = "http://xxx.com/"
path=r'x:\download'

con=threading.Condition()
def downloadpatch(path,url1):
    if con.acquire():
        while 1:
            print '               start thread of downloadpatch'
            print 'present time is: ',datetime.datetime.now()
            passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
            passmgr.add_password(None, proxy_info['server'] , proxy_info['user'], proxy_info['password'])
            auth = urllib2.ProxyBasicAuthHandler(passmgr)
            opener = urllib2.build_opener(urllib2.ProxyHandler({'http':proxy_info['server']}) , auth)
            urllib2.install_opener(opener)
            proname = urllib2.urlopen(url1)
            text=proname.read()
            print 'connect to website successfully'
            #print text
            name=re.findall('HREF="(\d+xdat.exe)"',text,re.IGNORECASE)
            #name=re.findall('HREF="(readme.txt)"',text,re.IGNORECASE)
            print 'the following files are all patchs in the website: '
            print name
        
            files=os.listdir(path)
            for i in files:
                for x in name:
                    if i==x:
                        name.remove(x)
            if len(name)>0:   
                print 'the following files are need to download:'
                print name
                print 'please wait......'
                for i in name:
                    f=open(path+'\\'+i,'wb')
                    downpro=urllib2.urlopen(url1+i)
                    while 1:
                        data=downpro.read(1024)
                        if not len(data):
                            break
                        f.write(data)
                    f.close()
                    print '%s files have download!!!'%i
                    f1=open(path+'\\'+'log'+'\\'+'log.txt','a')
                    f1.write(str(datetime.datetime.now())+' ')
                    f1.write('%s files have download!!!'%i)
                    f1.write('\n')
                    f1.close()
            else:
                print 'no files have to download' 
            proname.close()
            print '--------------------------------------------'
            con.notify()
        
            con.wait()
            
            time.sleep(24*60*60)
            #time.sleep(10)

def deletepatch(yourpath):
    if con.acquire():
        while 1:
            print '               starting thread of delete files'
            print 'present time is  :',datetime.datetime.now()
            pathlist=os.listdir(yourpath)#list all files
            for i in range(len(pathlist)):#counts
                source=yourpath+'\\'+pathlist[i]#path of a file
                if os.path.isfile(source):#whether is file
                    m=time.localtime(os.stat(source).st_ctime)# create time of file
                    endtime=datetime.datetime.now()# now time
                    startime=datetime.datetime(m.tm_year,m.tm_mon,m.tm_mday,m.tm_hour,m.tm_min,m.tm_sec)
                    #translate the time 
                    mydays=(endtime-startime).days
                    if mydays>=7:#if time is over 7 days
                        os.remove(source)# remove the file
                        print 'File',source,'have been deleted'
                        f2=open(path+'\\'+'log'+'\\'+'log.txt','a')
                        f2.write(str(datetime.datetime.now()))
                        f2.write('File',source,'have been deleted')
                        f2.write('\n')
                        f2.close()
                    else:
                        print 'File',source,'is now useful for us'
                else:
                    print 'File',source,'is not execute program'
            print '--------------------------------------------'
            con.notify()
            con.wait()
            
            time.sleep(24*60*60)
            #time.sleep(10)
        
if __name__=='__main__':
    try:
        t1=threading.Thread(None,target=downloadpatch,args=(path,url1))
        t1.start()
        
        
        t2=threading.Thread(None,target=deletepatch,args=(path,))
        t2.start()
        
    except Exception,e:
        print e
目录
相关文章
|
22天前
|
Python
【python】python跨文件使用全局变量
【python】python跨文件使用全局变量
|
1月前
|
监控 数据处理 索引
使用Python批量实现文件夹下所有Excel文件的第二张表合并
使用Python和pandas批量合并文件夹中所有Excel文件的第二张表,通过os库遍历文件,pandas的read_excel读取表,concat函数合并数据。主要步骤包括:1) 遍历获取Excel文件,2) 读取第二张表,3) 合并所有表格,最后将结果保存为新的Excel文件。注意文件路径、表格结构一致性及异常处理。可扩展为动态指定合并表、优化性能、日志记录等功能。适合数据处理初学者提升自动化处理技能。
22 1
|
1月前
|
存储 并行计算 Java
Python读取.nc文件的方法与技术详解
本文介绍了Python中读取.nc(NetCDF)文件的两种方法:使用netCDF4和xarray库。netCDF4库通过`Dataset`函数打开文件,`variables`属性获取变量,再通过字典键读取数据。xarray库利用`open_dataset`打开文件,直接通过变量名访问数据。文中还涉及性能优化,如分块读取、使用Dask进行并行计算以及仅加载所需变量。注意文件路径、变量命名和数据类型,读取后记得关闭文件(netCDF4需显式关闭)。随着科学数据的增长,掌握高效处理.nc文件的技能至关重要。
141 0
|
1月前
|
Python
python中文件和异常处理方法(二)
python中文件和异常处理方法(二)
13 0
|
1月前
|
Python
python中文件和异常处理方法(一)
python中文件和异常处理方法(一)
29 0
|
1月前
|
Python
python中文件和异常处理方法(三)
python中文件和异常处理方法(三)
20 0
|
6天前
|
存储 Python
用Python实现批量下载文件——代理ip排除万难
用Python实现批量下载文件——代理ip排除万难
|
6天前
|
JSON 关系型数据库 数据库
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
33 0
|
6天前
|
数据挖掘 索引 Python
Python 读写 Excel 文件
Python 读写 Excel 文件
12 0
|
6天前
|
数据安全/隐私保护 Python
Python文件与目录操作:面试中的高频考点
【4月更文挑战第15天】本文介绍了Python文件和目录操作的面试重点,包括文件的读写、目录遍历及权限管理。强调了文件关闭、异常处理、特殊文件判断以及权限位和权限字符串的理解。提供了代码示例,如读写文件、遍历目录和更改文件权限,帮助读者在面试中表现出色。掌握这些技能将对编程求职之路大有裨益。
17 0

热门文章

最新文章