且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

urllib:从直接下载链接获取文件名

更新时间:2022-10-15 11:55:12

Using urllib.request, when you request a response from a url, the response contains a reference to the url you are downloading.

>>> from urllib.request import urlopen    
>>> url = 'https://kerbal.curseforge.com/projects/mechjeb/files/2355387/download'
>>> response = urlopen(url)
>>> response.url
'https://addons-origin.cursecdn.com/files/2355/387/MechJeb2-2.6.0.0.zip'

You can use os.path.basename to get the filename:

>>> from os.path import basename
>>> basename(response.url)
'MechJeb2-2.6.0.0.zip'