您好,登錄后才能下訂單哦!
這篇文章主要介紹了urlretrieve下載函數(shù)怎么在python中使用,億速云小編覺(jué)得不錯(cuò),現(xiàn)在分享給大家,也給大家做個(gè)參考,一起跟隨億速云小編來(lái)看看吧!
Python主要應(yīng)用于:1、Web開發(fā);2、數(shù)據(jù)科學(xué)研究;3、網(wǎng)絡(luò)爬蟲;4、嵌入式應(yīng)用開發(fā);5、游戲開發(fā);6、桌面應(yīng)用開發(fā)。
實(shí)驗(yàn)環(huán)境:windows 7,anaconda 3(python 3.5),tensorflow(gpu/cpu)
函數(shù)介紹:所用函數(shù)為six.moves下的urllib中的函數(shù),調(diào)用如下urllib.request.urlretrieve(url,[filepath,[recall_func,[data]]])。簡(jiǎn)單介紹一下,url是必填的指的是下載地址,filepath指的是保存的本地地址,recall_func指的是回調(diào)函數(shù),下載過(guò)程中會(huì)調(diào)用可以用來(lái)顯示下載進(jìn)度。
實(shí)驗(yàn)代碼:以下載cifar10的dataset和抓取斗魚首頁(yè)為例
下載cifar10的dataset,并解壓
from six.moves import urllib import os import sys import tensorflow as tf import tarfile FLAGS = tf.app.flags.FLAGS#提取系統(tǒng)參數(shù)作用的變量 tf.app.flags.DEFINE_string('dir','D:/download_html','directory of html')#將下載目錄保存到變量dir中,通過(guò)FLAGS.dir提取 directory = FLAGS.dir#從FLAGS中提取dir變量 url = 'http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz' filename = url.split('/')[-1]#-1表示分割后的最后一個(gè)元素 filepath = os.path.join(directory,filename) if not os.path.exists(directory): os.makedirs(directory) if not os.path.exists(filepath): def _recall_func(num,block_size,total_size): sys.stdout.write('\r>> downloading %s %.1f%%' % (filename,float(num*block_size)/float(total_size)*100.0)) sys.stdout.flush() urllib.request.urlretrieve(url,filepath,_recall_func) print() file_info = os.stat(filepath) print('Successfully download',filename,file_info.st_size,'bytes') tar = tarfile.open(filepath,'r:gz')#指定解壓路徑和解壓方式為解壓gzip tar.extractall(directory)#全部解壓
抓取斗魚首頁(yè)
from six.moves import urllib import os import sys import tensorflow as tf FLAGS = tf.app.flags.FLAGS#提取系統(tǒng)參數(shù)作用的變量 tf.app.flags.DEFINE_string('dir','D:/download_html','directory of html')#將下載目錄保存到變量dir中,通過(guò)FLAGS.dir提取 directory = FLAGS.dir#從FLAGS中提取dir變量 url = 'http://www.douyu.com/' filename = 'douyu.html'#保存成你想要的名字,這里保存成douyu.html filepath = os.path.join(directory,filename) if not os.path.exists(directory): os.makedirs(directory) if not os.path.exists(filepath): def _recall_func(num,block_size,total_size): sys.stdout.write('\r>> downloading %s %.1f%%' % (filename,float(num*block_size)/float(total_size)*100.0)) sys.stdout.flush() urllib.request.urlretrieve(url,filepath,_recall_func) print() file_info = os.stat(filepath)#獲取文件信息 print('Successfully download',filename,file_info.st_size,'bytes')#.st_size文件的大小,以字節(jié)為單位
以上就是億速云小編為大家收集整理的urlretrieve下載函數(shù)怎么在python中使用,如何覺(jué)得億速云網(wǎng)站的內(nèi)容還不錯(cuò),歡迎將億速云網(wǎng)站推薦給身邊好友。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。