Python实现的批量下载RFC文档

yipeiwu_com5年前Python基础

RFC文档有很多,有时候在没有联网的情况下也想翻阅,只能下载一份留存本地了。
看了看地址列表,大概是这个范围:
http://www.networksorcery.com/enp/rfc/rfc1000.txt
...
http://www.networksorcery.com/enp/rfc/rfc6409.txt

哈哈,很适合批量下载,第一个想到的就是迅雷……
可用的时候发现它只支持三位数的扩展(用的是迅雷7),我想要下的刚好是四位数……
郁闷之下萌生自己做一个的想法!
这东西很适合用python做,原理很简单,代码也很少,先读为快。
代码如下:

复制代码 代码如下:

#! /usr/bin/python
'''
  File      : getRFC.py
  Author    : Mike
  E-Mail    : Mike_Zhang@live.com
'''
import urllib,os,shutil,time

def downloadHtmlPage(url,tmpf = ''):
    i = url.rfind('/')
    fileName = url[i+1:]
    if tmpf : fileName = tmpf
    print url,"->",fileName
    urllib.urlretrieve(url,fileName)
    print 'Downloaded ',fileName   
    time.sleep(0.2)
    return fileName
   
# http://www.networksorcery.com/enp/rfc/rfc1000.txt
# http://www.networksorcery.com/enp/rfc/rfc6409.txt
if __name__ == '__main__':
    addr = 'http://www.networksorcery.com/enp/rfc'   
    dirPath = "RFC"
    #startIndex = 1000
    startIndex = int(raw_input('start : '))
    #endIndex = 6409
    endIndex = int(raw_input('end : '))
    if startIndex > endIndex :
        print 'Input error!'       
    if False == os.path.exists(dirPath):
        os.makedirs(dirPath)   
    fileDownloadList = []
    logFile = open("log.txt","w")
    for i in range(startIndex,endIndex+1):
        try:           
            t_url = '%s/rfc%d.txt' % (addr,i)
            fileName = downloadHtmlPage(t_url)
            oldName = './'+fileName
            newName = './'+dirPath+'/'+fileName
            if True == os.path.exists(oldName):
                shutil.move(oldName,newName)
                print 'Moved ',oldName,' to ',newName
        except:
            msgLog = 'get %s failed!' % (i)
            print msgLog
            logFile.write(msgLog+'\n')
            continue
    logFile.close()

除了RFC文档,这个程序稍加修改也可以做其它事情:比如批量下载MP3、电子书等等。

好,就这些了,希望对你有帮助。

相关文章

python中装饰器级连的使用方法示例

前言 最近在学习python,学会了为什么要使用装饰器,也明白了装饰器是什么了,但是你也许会问,是否可以在装饰器前面再添加一层装饰器,会怎么样呢?就像大楼一样,一层一层地叠在一起。其实是...

Python算术运算符实例详解

Python算术运算符 以下假设变量a为10,变量b为20: 运算符 描述 实例 +...

Python 多线程实例详解

Python 多线程实例详解 多线程通常是新开一个后台线程去处理比较耗时的操作,Python做后台线程处理也是很简单的,今天从官方文档中找到了一个Demo. 实例代码: import...

Python 模板引擎的注入问题分析

这几年比较火的一个漏洞就是jinjia2之类的模板引擎的注入,通过注入模板引擎的一些特定的指令格式,比如 {{1+1}} 而返回了 2 得知漏洞存在。实际类似的问题在Python原生字符...

Python脚本实现自动发带图的微博

Python脚本实现自动发带图的微博

 要自动发微博最简单的办法无非是调用新浪微博的API(因为只是简单的发微博,就没必要用它的SDK了)。参考开发文档http://open.weibo.com/wiki/API...