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、电子书等等。

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

相关文章

详解Python3定时器任务代码

使用threading写的一个定时器任务demo: import time import sys import signal import datetime import threa...

搞笑的程序猿:看看你是哪种Python程序员

不久前,在互联网上出现了一篇有趣的文章,讲的是对于同一个问题,不同层次的Python程序员编出的Python代码,显示出了不同的风格,代码都很简单,有趣。下面让我们一起来看看一个Pyth...

Python OpenCV利用笔记本摄像头实现人脸检测

Python OpenCV利用笔记本摄像头实现人脸检测

本文实例为大家分享了Python OpenCV利用笔记本摄像头实现人脸检测的具体代码,供大家参考,具体内容如下 1.安装opencv 首先参考其他文章安装pip。 之后以管理员身份运行命...

研究Python的ORM框架中的SQLAlchemy库的映射关系

前面介绍了关于用户账户的User表,但是现实生活中随着问题的复杂化数据库存储的数据不可能这么简单,让我们设想有另外一张表,这张表和User有联系,也能够被映射和查询,那么这张表可以存储关...

利用python画一颗心的方法示例

利用python画一颗心的方法示例

前言 Python一般使用Matplotlib制作统计图形,用它自己的说法是‘让简单的事情简单,让复杂的事情变得可能'。用它可以制作折线图,直方图,条形图,散点图,饼图,谱图等等你能想到...