【问题标题】:Identify the file extension of a URL识别 URL 的文件扩展名
【发布时间】:2015-04-02 01:30:42
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: python python-2.7 url file-extension


    【解决方案1】:

    urlparse 模块(Python 3 中的urllib.parse)提供了处理 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 '.'
    

    示例用法:

    >>> 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")
    ''
    

    【讨论】:

      猜你喜欢
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      • 2020-04-22
      • 2014-09-10
      • 1970-01-01
      • 2015-05-24
      相关资源
      最近更新 更多