Python はリンクされたファイルのサイズを確認し、ファイルをダウンロードします

序文

URL が与えられた場合、リンクが有効かどうかを確認するにはどうすればよいですか? リンクされたファイルの大きさはどれくらいですか? ファイルをダウンロードするにはどうすればよいですか?

参考:
urllibライブラリのurlopenの詳細説明

ソースコード

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

ここでの Python と urllib のバージョンは次のとおりです:
python: 3.7.16
urllib3: 2.0.4

おすすめ

転載: blog.csdn.net/qq_33757398/article/details/132319882
おすすめ