Python中urlretrieve函数

API定义:
urllib.request.urlretrieve(url,filename=None,reporthook=None, data=None)
利用urlretrieve() 将数据下载到本地。
- 参数 finename 指定了保存本地路径(如果参数未指定,urllib会生成一个临时文件保存数据。)
 
- 参数 reporthook 是一个回调函数,当连接上服务器、以及相应的数据块传输完毕时会触发该回调,我们可以利用这个回调函数来显示当前的下载进度。
 
- 参数 data 指 post 到服务器的数据,该方法返回一个包含两个元素的(filename, headers)元组,filename 表示保存到本地的路径,header 表示服务器的响应头。
用法:
>>> import urllib.request
>>>local_filename,headers=urllib.request.urlretrieve('http://python.org/')
>>> html = open(local_filename)
>>> html.close()
注意:当html=open(local_filename),然后lines=html.readlines()时可能会出现unicode错误
处理方法:html=open(local_filename,'utf-8')这样就会解决unicode问题。
例子:抓取web页面
#coding:utf-8
from urllib.request import urlretrieve

def firstNonBlank(lines):
    for  eachLine in lines:
        if not eachLine.strip():
            continue
        else:
            return eachLine

def firstLast(webpage):
    f=open(webpage,encoding='utf-8')
    lines=f.readlines()
    f.close()
    print(firstNonBlank(lines))
    lines.reverse()
    print(firstNonBlank(lines))

def download(url='http://www.baidu.com',process=firstLast):
    try:
        retval=urlretrieve(url)[0]
    except IOError:
        retval=None
    if retval:
        process(retval)

if __name__=="__main__":
    download()
原文地址:https://www.cnblogs.com/itdyb/p/5411723.html