How to safely get the file extension from a URL?

后端 未结 9 1231
北荒
北荒 2021-02-02 08:40

Consider the following URLs

http://m3u.com/tunein.m3u
http://asxsomeurl.com/listen.asx:8024
http://www.plssomeotherurl.com/station.pls?id=111
http://22.198.133.16:802         


        
9条回答
  •  清歌不尽
    2021-02-02 09:00

    $ python3
    Python 3.1.2 (release31-maint, Sep 17 2010, 20:27:33) 
    [GCC 4.4.5] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from os.path import splitext
    >>> from urllib.parse import urlparse 
    >>> 
    >>> urls = [
    ...     'http://m3u.com/tunein.m3u',
    ...     'http://asxsomeurl.com/listen.asx:8024',
    ...     'http://www.plssomeotherurl.com/station.pls?id=111',
    ...     'http://22.198.133.16:8024',
    ... ]
    >>> 
    >>> for url in urls:
    ...     path = urlparse(url).path
    ...     ext = splitext(path)[1]
    ...     print(ext)
    ... 
    .m3u
    .asx:8024
    .pls
    
    >>> 
    

提交回复
热议问题