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 socket分发大文件的实现方法

思路: 使用socket传输文件过程中,如果单次传输每次只能发送一部分数据,如果针对大文件,一次传输肯定是不行的,所以需要我们在传输的时候提前把传输内容的大小先发送给客户端,在客户端循环...

Python专用方法与迭代机制实例分析

本文实例讲述了Python专用方法与迭代机制,分享给大家供大家参考之用。具体分析如下: 众所周知,Python 设计哲学是“优雅”、“明确”、“简单”,对于一件事只用一种最好的方法来做,...

python的set处理二维数组转一维数组的方法示例

for splitValue in set(dataset[:, featureIndex].tolist()): 首先set是一个无序,无重复的数据结构,所以很多时候使用它来进行去重;...

Django发送html邮件的方法

本文实例讲述了Django发送html邮件的方法。分享给大家供大家参考。具体如下: 在Django中,发送邮件非常的方便,一直没有时间,今天来做一个小小的总结吧。 我们常用的当然是通过s...

python pygame实现2048游戏

python pygame实现2048游戏

实现2048相对来说比较简单,用4*4的二维数组保存地图,pygame.key.get_pressed()获取键盘操作,详见代码。 效果图 代码 # -*- coding: ut...