prefacio
Dada una URL, ¿cómo verifico si el enlace es válido? ¿Qué tamaño tiene el archivo vinculado? y como descargo el archivo?
Referencia:
explicación detallada de urlopen en la biblioteca urllib
código fuente
from urllib import request
url = 'Input your target url. For example: https://www.baidu.com/'
target_path = 'Input the path you want to save'
try:
response = request.urlopen(url)
# print(response.status)
# print(response.getheaders())
size = int(response.getheader('CONTENT-LENGTH')) # 返回的大小单位为字节
size = size / (1024*1024) ## 转换为MB单位
print('file size: %.2fMB' % size)
request.urlretrieve(url, target_path)
except:
raise AttributeError('This url is invalid')
Tenga en cuenta que las versiones de Python y urllib aquí son:
python: 3.7.16
urllib3: 2.0.4