How to safely get the file extension from a URL?

后端 未结 9 1230
北荒
北荒 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:26

    This is easiest with requests and mimetypes:

    import requests
    import mimetypes
    
    response = requests.get(url)
    content_type = response.headers['content-type']
    extension = mimetypes.guess_extension(content_type)
    

    The extension includes a dot prefix. For example, extension is '.png' for content type 'image/png'.

提交回复
热议问题