回调函数的使用。


'''
1 传入网址,网址的类型一定是字符串
2 传入的,本地的网页路径保存+文件名。
3 一个函数的调用,我们可以任意来定义这个函数的行为,但是一定要保证这个函数有三个参数

(1)到目前为止传递的数据块的数量
(2)是每个数据块的大小,单位为byte,字节。
(3)远程文件的大小,有时返回为1

import urllib
def callback(a,b,c):
    
    #@a:是到目前为止传递的数据块的数量
    #@b:是每个数据块的大小,单位为byte,字节。
    #@c:是远程文件的大小,有时返回为1
    
    down_progress=100.0*a*b/c
    if down_progress>100:
        down_progress=100
    print "%.2f%%"%down_progress

url = "http://www.iplaypython.com/"
local="E:\iplaypython.html"
urllib.urlretrieve(url,local,callback)

执行上面的脚本的结果为:
0.00%
11.64%
23.28%
34.92%
46.56%
58.20%
69.84%
81.48%
93.12%
100.00%
#这是下载进度条显示,同时在e盘中可以看到相应的iplaypython.html文件。
'''




###################################################################################
#回调函数callback的三个参数的讲解:

import urllib
def callbacks(*a):
    print a


url = "http://www.iplaypython.com/"
local="E://iplaypython.txt"
html = urllib.urlretrieve(url,local,callbacks)
'''
返回结果为:
(0, 8192, 70377)
(1, 8192, 70377)
(2, 8192, 70377)
(3, 8192, 70377)
(4, 8192, 70377)
(5, 8192, 70377)
(6, 8192, 70377)
(7, 8192, 70377)
(8, 8192, 70377)
(9, 8192, 70377)
传回来带三个值的元组;而这个元组分别对应这目前为此传递的数据块数量,每个数据块的大小,单位是byte;以及远程文件的大小
'''
#如何查看远程文件的大小,可通过头文件中可以知道
print urllib.urlopen(url).info()
'''相当于:html.info()
Date: Sat, 02 Sep 2017 04:56:11 GMT
Server: Apache
Last-Modified: Mon, 28 Aug 2017 02:05:22 GMT
ETag: "52316-112e9-557c6ba29dc80"
Accept-Ranges: bytes
Content-Length: 70377    #文章长度,即网页的大小,就表明远程文件的大小就是网页的大小
Vary: Accept-Encoding
Connection: close
Content-Type: text/html
'''

原文地址:https://www.cnblogs.com/papapython/p/7466566.html