Urllib: Get filename from direct download link

Python 3. Maybe you need to use urllib for this,

I need to know how to request a direct download link and get the name of the file it is trying to save.

(As an example, the KSP mod from CurseForge: https://kerbal.curseforge.com/projects/mechjeb/files/2355387/download )

Of course the file id ( 2355387

) will be changed. It can be any project, but always on CurseForge. (If it affects the download method.)

This example link leads to a file:

Download Screenshot

How can I get this name back in Python?

Change: . I should note that I want to avoid saving the file by reading its name and then deleting it if possible. This seems like the worst way to do it.

+3


source to share


1 answer


Using when you request a response from a url, the response contains a link to the url you are loading. urllib.request

>>> 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 to get the filename: os.path.basename

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

      

+4


source







All Articles