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 skimage 连通性区域检测方法

涉及到的函数为 import matplotlib.pyplot as plt from skimage import measure, color labels = measure...

python matplotlib中文显示参数设置解析

python matplotlib中文显示参数设置解析

最近在学习python著名的绘图包matplotlib时发现,有时候图例等设置无法正常显示中文,于是就想把这个问题解决了。 PS:本文仅针对Windows,其他平台仅供参考。 原因 大致...

python3的数据类型及数据类型转换实例详解

python3的数据类型及数据类型转换实例详解

之前介绍过python开发工具Jupyter的使用,今天继续讲解python的数据类型,python中有整型、浮点型、字符串、布尔类型,我们重点介绍布尔类型的运算,以及不同数据类型之间的...

Python实现求解一元二次方程的方法示例

本文实例讲述了Python实现求解一元二次方程的方法。分享给大家供大家参考,具体如下: 1. 引入math包 2. 定义返回的对象 3. 判断b*b-4ac的大小 具体计算代码如下:...

Python决策树和随机森林算法实例详解

Python决策树和随机森林算法实例详解

本文实例讲述了Python决策树和随机森林算法。分享给大家供大家参考,具体如下: 决策树和随机森林都是常用的分类算法,它们的判断逻辑和人的思维方式非常类似,人们常常在遇到多个条件组合问题...