urllib:从直接下载链接获取文件名 [英] urllib: Get name of file from direct download link

查看:170
本文介绍了urllib:从直接下载链接获取文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3。可能需要使用urllib来做到这一点,



我需要知道如何发送请求以直接下载链接,并获取它尝试保存的文件的名称。



(例如,来自CurseForge的KSP mod: ,当您从网址请求响应时,响应中包含对您正在下载的网址的引用。

 > >从urllib.request导入urlopen 
>>> url =‘https://kerbal.curseforge.com/projects/mechjeb/files/235538​​7/download’
>>>响应= urlopen(url)
>> response.url
'https://addons-origin.cursecdn.com/files/2355/387/MechJeb2-2.6.0.0.zip'

您可以使用 os.path.basename 来获取文件名:

 >>从os.path导入基本名
>> basename(response.url)
‘MechJeb2-2.6.0.0.zip’


Python 3. Probably need to use urllib to do this,

I need to know how to send a request to a direct download link, and get the name of the file it attempts to save.

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

Of course, the file ID (2355387) will be changed. It could be from any project, but always on CurseForge. (If that makes a difference on the way it's downloaded.)

That example link results in the file:

How can I return that file name in Python?

Edit: I should note that I want to avoid saving the file, reading the name, then deleting it if possible. That seems like the worst way to do this.

解决方案

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'

这篇关于urllib:从直接下载链接获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆