python学习笔记之url.urlretrieve

开始填坑之旅
关于url.urlretrieve(ilename[, reporthook[, data]]])的使用
urllib.urlretrieve(url,filename)下载网络文件,第一个元素就是目标url,第二个参数是保存的文件绝对路径(含文件名),返回值是一个tuple(filename,header),其中的filename就是第二个参数filename.如果urlretrieve仅提供1个参数,返回值的filename就是产生的临时文件名,函数执行完毕后该临时文件会被删除参数。参数reporthook是一个回调函数,当连接上服务器、以及相应的数据块传输完毕的时候会触发该回调。其中回调函数名称可任意,但是参数必须为三个。一般直接使用reporthook(block_read,block_size,total_size)定义回调函数,block_size是每次读取的数据块的大小,block_read是每次读取的数据块个数,taotal_size是一一共读取的数据量,单位是byte。可以使用reporthook函数来显示读取进度。
import urllib
import os
def reporthook(block_read,block_size,total_size):
  pass;
def hello(blok,fsd,saf):
  print "hello";
  
try:
 filename,msg=urllib.urlretrieve('http://blog.doughellmann.com/',reporthook=hello);
 print 
 print 'File',filename;
 print msg
 print "exists?",os.path.exists(filename);
finally:
  urllib.urlcleanup();
  
print "exists?",os.path.exists(filename);


使用reporthook(block_read,block_size,total_size)显示进度

import urllib
import os
def hello(blok,fsd,saf):
  print "hello";
  
def reporthook(block_read,block_size,total_size):
  if not block_read:
    print "connection opened";
    return
  if total_size<0:
    #unknown size
    print "read %d blocks (%dbytes)" %(block_read,block_read*block_size);
  else:
    amount_read=block_read*block_size;
    print 'Read %d blocks,or %d/%d' %(block_read,block_read*block_size,total_size);
  return
  
try:
 filename,msg=urllib.urlretrieve('http://blog.doughellmann.com/',reporthook=reporthook);
 print 
 print 'File',filename;
 print 'Header:'
 print msg
 print "exists?",os.path.exists(filename);
finally:
  urllib.urlcleanup();
  
print "exists?",os.path.exists(filename);





注:当服务器没有返回content-length首部时,urlretrieve不知道数据有多大,为total_size传入-1。
参考: http://ddtcms.com/blog/archive/2011/12/19/21/python-urllib-urlretrieve-download-files/
          http://www.cnblogs.com/cyiner/archive/2012/08/19.html
             《python标准库》机械工业出版社 Doug Hellmann著,刘炽等译
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值