urlretrieve python3_python3 retrieve()

本文介绍如何使用Python的urllib.request模块中的urlretrieve函数下载文件,并实现进度显示及错误处理。该函数可能在未来版本中被弃用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

retreive()被认为是个老旧函数,可能会在将来抛弃。

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

Exceptions和函数urlopen()相同。

具体文档,参见https://docs.python.org/3/library/urllib.request.html#module-urllib.request

代码片段

from urllib.request import urlretrieve

import socket

import os

import sys

def reporthook(blocknum, bs, size):

# blocknum:已经下载的数据块 bs:数据块的大小 size:远程文件的大小

per = 100.0 * blocknum * bs / size

if per > 100 :

per = 100

sys.stdout.write('Download progress: %.2f%% \r'%per)

sys.stdout.flush()

class ClassName():

def __init__(self):

socket.setdefaulttimeout(30)

def run(self):

...

while True:

.....

try:

urlretrieve(url,localfile, reporthook= reporthook)

except socket.timeout:

self.redownload(url,localfile)

except Exception as e:

StatusCode=e.getcode()

if StatusCode == 404:

print(e)

break

self.redownload(url,localfile)

def redownload(self,url,localfile):

count = 1

while count <= 5:

try:

urlretrieve(url,localfile, reporthook= reporthook)

break

except socket.timeout:

err_info = 'Reloading for %d time.....'%count if count == 1 else 'Reloading for %d times.....'%count

print(err_info)

count += 1

if count > 5:

print("download job failed!")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值