Python checks the size of the linked file and downloads the file

foreword

Given a url, how do I check to see if the link is valid? How big is the linked file? and how to download the file?

Reference:
Detailed explanation of urlopen in urllib library

source code

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')

Note that the versions of Python and urllib here are:
python: 3.7.16
urllib3: 2.0.4

Guess you like

Origin blog.csdn.net/qq_33757398/article/details/132319882
Recommended