Python:urllib模块的urlretrieve方法

转于:https://blog.csdn.net/fengzhizi76506/article/details/59229846

博主:fengzhizi76506

1)功能

 urllib模块提供的urlretrieve()函数,urlretrieve()方法直接将远程数据下载到本地。

2)格式

 import urllib.request

 urllib.request.urlretrieve(url, filename=None, reporthook=None, data=None)

  • filename:指定了保存本地路径(如果参数未指定,urllib会生成一个临时文件保存数据。)
  • reporthook:一个回调函数,当连接上服务器、以及相应的数据块传输完毕时会触发该回调,我们可以利用这个回调函数来显示当前的下载进度。
  • data:指post导服务器的数据,该方法返回一个包含两个元素的(filename, headers) 元组,filename 表示保存到本地的路径,header表示服务器的响应头

:将baidu的html抓取到本地,保存在''./baidu.html"文件中,同时显示下载的进度。

#!/usr/bin/env python  
# coding=utf-8  
import os  
import urllib.reuest
  
def cbk(a,b,c):  
    '''''回调函数 
    @a:已经下载的数据块 
    @b:数据块的大小 
    @c:远程文件的大小 
    '''  
    per=100.0*a*b/c  
    if per>100:  
        per=100  
    print('%.2f%%' % per)
  
url='http://www.baidu.com'  
dir=os.path.abspath('.')  
work_path=os.path.join(dir,'baidu.html')  
urllib.request.urlretrieve(url,work_path,cbk)  
#!/usr/bin/env python  
# coding=utf-8  
import os  
import urllib.request
  
def cbk(a,b,c):  
    '''''回调函数 
    @a:已经下载的数据块 
    @b:数据块的大小 
    @c:远程文件的大小 
    '''  
    per=100.0*a*b/c  
    if per>100:  
        per=100  
    print('%.2f%%' % per)
  
url='http://www.baidu.com'  
dir=os.path.abspath('.')  
work_path=os.path.join(dir,'baidu.html')  
urllib.request.urlretrieve(url,work_path,cbk)  
#!/usr/bin/env python  
# coding=utf-8  
import os  
import urllib.request
  
def cbk(a,b,c):  
    '''''回调函数 
    @a:已经下载的数据块 
    @b:数据块的大小 
    @c:远程文件的大小 
    '''  
    per=100.0*a*b/c  
    if per>100:  
        per=100  
    print('%.2f%%' % per)
  
url='http://www.python.org/ftp/python/2.7.5/Python-2.7.5.tar.bz2'  
dir=os.path.abspath('.')  
work_path=os.path.join(dir,'Python-2.7.5.tar.bz2')  
urllib.request.urlretrieve(url,work_path,cbk)  

Python:urllib模块的urlretrieve方法

 3)urlopen()可以轻松获取远端html页面信息,然后通过Python正则对所需要的数据进行分析,匹配出想要用的数据,再利用urlretrieve()将数据下载到本地。

  A、对于访问受限或者对连接数有限制的远程url地址,可以采用proxies(代理IP)连接;

  B、如果远程连接数据量过大,单线程下载太慢的话可以采用多线程下载;

  这个就是传说中的爬虫