识别 URL 的文件扩展名

kyr*_*nia 3 python url file-extension python-2.7

我希望提取文件扩展名,如果它存在于网址中(试图确定哪些链接指向我不想要的扩展名列表,例如.jpg.exe等)。

因此,我想从以下 URL 中提取www.example.com/image.jpgextension jpg,并处理没有扩展名的情况,例如www.example.com/file(即不返回任何内容)。

我想不出如何实现它,但我想到的一种方法是在最后一个点之后获取所有内容,如果有扩展名,我将允许我查找该扩展名,如果没有,例如www.example.com/file它会返回com/file (给出的不在我的排除文件扩展名列表中,很好)。

使用我不知道的包可能有另一种更好的方法,它可以确定什么是/不是实际扩展。(即处理 URL 实际上没有扩展名的情况)。

Zer*_*eus 6

urlparse模块(urllib.parse在 Python 3 中)提供了用于处理 URL 的工具。虽然它没有提供从 URL 中提取文件扩展名的方法,但可以通过将其与 组合来实现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 '.'
Run Code Online (Sandbox Code Playgroud)

用法示例:

>>> 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")
''
Run Code Online (Sandbox Code Playgroud)