简体   繁体   English

从 url 保存图像的名称

[英]Save the name of an image from a url

I need to find a way to get the image name of any given image from a url.我需要找到一种方法来从 url 获取任何给定图像的图像名称。 For example, in ".../images/foo.png", the image name is "foo.png".例如,在“.../images/foo.png”中,图像名称为“foo.png”。 Is there a way to read this url and save just the name of the image up until the "/"?有没有办法读取这个 url 并只保存图像的名称直到“/”? Thanks!谢谢!

You can just use split :你可以只使用split

url = 'https://upload.wikimedia.org/wikipedia/en/d/d0/Dogecoin_Logo.png'
*_, filename = url.split('/')
print(filename)
# Outputs Dogecoin_Logo.png

this is a beginner-friendly way.这是一种初学者友好的方式。 the split method returns a list of sections from the string so you just take the last one since it's what you want. split 方法从字符串中返回一个部分列表,所以你只需要最后一个,因为它是你想要的。

url = 'https://upload.wikimedia.org/wikipedia/en/d/d0/Dogecoin_Logo.png'
filename = url.split("/")[-1]
print(filename)

It's not a good idea to use split on its own with arbitrary URLs, because they might have query or path parameters which mean you don't get the correct file name: you only want the last segment of the URL path.对任意 URL 单独使用split不是一个好主意,因为它们可能具有查询或路径参数,这意味着您无法获得正确的文件名:您只需要 URL 路径的最后一段。 Python has a built in URL parser which should help with this . Python 有一个内置的 URL 解析器,它应该有助于解决这个问题

from urllib.parse import urlparse

url = "https://example.com/some/path/with/image%20name.png?width=640px&height=640px"

parsed_url = urlparse(url)
url_path = parsed_url.path

image_name = url_path.split("/")[-1]
print(image_name)  # 'image%20name.png'

Additionally, though, you probably want to decode any special characters in the file name (like spaces) using unquote :此外,您可能希望使用unquote解码文件名中的任何特殊字符(如空格):

from urllib.parse import unquote

image_name = unquote(image_name)
print(image_name)  # 'image name.png'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM