识别 URL 的文件扩展名
Identify the file extension of a URL
我希望提取文件扩展名(如果它存在于网址中)(尝试确定哪些链接指向我不想要的扩展名列表,例如 .jpg
、.exe
等) .
所以,我想从下面的 URL www.example.com/image.jpg
中提取扩展名 jpg
,并处理没有扩展名的情况,例如 www.example.com/file
(即 return 什么都没有)。
我想不出如何实现它,但我想到的一种方法是在最后一个点之后获取所有内容,如果有扩展名,我可以查看该扩展名,如果没有' t,例如 www.example.com/file
它将 return com/file
(给出的不在我的排除文件扩展名列表中,没问题)。
可能有另一种更好的方法使用我不知道的包,它可以识别 is/isn 不是实际扩展的内容。 (即应对 URL 实际上没有扩展名的情况)。
urlparse
module (urllib.parse
in Python 3) provides tools for working with URLs. Although it doesn't provide a way to extract the file extension from a URL, it's possible to do so by combining it with os.path.splitext
:
from urlparse import urlparse
from os.path import splitext
def get_ext(url):
"""Return the filename extension from url, or ''."""
parsed = urlparse(url)
root, ext = splitext(parsed.path)
return ext # or ext[1:] if you don't want the leading '.'
用法示例:
>>> get_ext("www.example.com/image.jpg")
'.jpg'
>>> get_ext("https://www.example.com/page.html?foo=1&bar=2#fragment")
'.html'
>>> get_ext("https://www.example.com/resource")
''
我希望提取文件扩展名(如果它存在于网址中)(尝试确定哪些链接指向我不想要的扩展名列表,例如 .jpg
、.exe
等) .
所以,我想从下面的 URL www.example.com/image.jpg
中提取扩展名 jpg
,并处理没有扩展名的情况,例如 www.example.com/file
(即 return 什么都没有)。
我想不出如何实现它,但我想到的一种方法是在最后一个点之后获取所有内容,如果有扩展名,我可以查看该扩展名,如果没有' t,例如 www.example.com/file
它将 return com/file
(给出的不在我的排除文件扩展名列表中,没问题)。
可能有另一种更好的方法使用我不知道的包,它可以识别 is/isn 不是实际扩展的内容。 (即应对 URL 实际上没有扩展名的情况)。
urlparse
module (urllib.parse
in Python 3) provides tools for working with URLs. Although it doesn't provide a way to extract the file extension from a URL, it's possible to do so by combining it with os.path.splitext
:
from urlparse import urlparse
from os.path import splitext
def get_ext(url):
"""Return the filename extension from url, or ''."""
parsed = urlparse(url)
root, ext = splitext(parsed.path)
return ext # or ext[1:] if you don't want the leading '.'
用法示例:
>>> get_ext("www.example.com/image.jpg")
'.jpg'
>>> get_ext("https://www.example.com/page.html?foo=1&bar=2#fragment")
'.html'
>>> get_ext("https://www.example.com/resource")
''