溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用urlretrieve()函數(shù)怎么下載網(wǎng)絡(luò)文件

發(fā)布時(shí)間:2021-03-25 17:18:57 來源:億速云 閱讀:232 作者:Leah 欄目:開發(fā)技術(shù)

今天就跟大家聊聊有關(guān)使用urlretrieve()函數(shù)怎么下載網(wǎng)絡(luò)文件,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

源碼

# !/usr/bin/env python
# -*- coding:utf-8 -*-
 
 
"""
圖片(文件)下載,核心方法是 urllib.urlrequest 模塊的 urlretrieve()方法
 urlretrieve(url, filename=None, reporthook=None, data=None)
 url: 文件url
 filename: 保存到本地時(shí),使用的文件(路徑)名稱
 reporthook: 文件傳輸時(shí)的回調(diào)函數(shù)
 data: post提交到服務(wù)器的數(shù)據(jù)
 該方法返回一個(gè)二元元組("本地文件路徑",<http.client.HTTPMessage對象>)
"""
 
import requests
import urllib.request
from lxml import etree
 
 
def crawl():
 url='http://www.ivsky.com/tupian/haiyangshijie/'
 headers={
 "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36",
 }
 
 resp=requests.get(url,headers=headers)
 
 if resp.status_code==200:
 resp.encoding='UTF-8'
 html=etree.HTML(resp.text)
 
 img_titles=html.xpath('//ul[@class="ali"]//a/@title')
 img_urls=html.xpath('//ul[@class="ali"]//a/img/@src')
 
 data=zip(img_titles,img_urls)
 for img_title,img_url in data:
  print('開始下載{title}.jpg'.format(title=img_title))
  result=urllib.request.urlretrieve(img_url,
     filename='../../data/圖片下載爬蟲/{title}.jpg'.format(title=img_title),
     reporthook=loading,
     data=None)
  # print(result)
 
def loading(blocknum,blocksize,totalsize):
 """
 回調(diào)函數(shù): 數(shù)據(jù)傳輸時(shí)自動調(diào)用
 blocknum:已經(jīng)傳輸?shù)臄?shù)據(jù)塊數(shù)目
 blocksize:每個(gè)數(shù)據(jù)塊字節(jié)
 totalsize:總字節(jié)
 """
 percent=int(100*blocknum*blocksize/totalsize)
 if percent>100:
 percent=100
 print("正在下載>>>{}%".format(percent))
 import time
 time.sleep(0.5)
 
 
if __name__ == '__main__':
 crawl()

看完上述內(nèi)容,你們對使用urlretrieve()函數(shù)怎么下載網(wǎng)絡(luò)文件有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI