如何检查imgur URL是gif还是图像?

时间:2017-06-28 05:06:35

标签: python gif imgur

说我有一个像这样的imgur网址:https://imgur.com/pCEoGjF

从网址我不知道这是图片还是gif。我知道我可以添加" .jpg"到文件的末尾以获得到图像的直接链接,但如果链接碰巧是gif,这也将显示gif。我将如何以编程方式(使用imgur API或其他方式)检查网址https://imgur.com/pCEoGjFhttps://imgur.com/pCEoGjF.jpg上的项目是图片还是gif?

编辑: 我试过这个

print(requests.head(submission.url + ".jpg").headers['Content-Type'])

但它抱怨以下错误:

KeyError: 'content-type'

暗示内容类型不是标题中的关键字。我打印了标题并确认了它们如下:

{'Content-Length': '0', 'X-Served-By': 'cache-sjc3138-SJC', 'X-Cache': 'HIT', 'Accept-Ranges': 'bytes', 'X-Timer': 'S1498627080.598287,VS0,VE0', 'Server': 'cat factory 1.0', 'Retry-After': '0', 'Connection': 'close', 'X-Cache-Hits': '0', 'Location': 'https://i.imgur.com/APMnK9t.jpg', 'Cache-Control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0', 'Date': 'Wed, 28 Jun 2017 05:17:59 GMT', 'X-Frame-Options': 'DENY'}

我想我可以检查内容长度是否为0,看看它是否是一个gif?想法?

1 个答案:

答案 0 :(得分:4)

使用requests library

import requests

def get_content_type(url):
    return requests.head(url).headers['Content-Type']

print(get_content_type('https://i.imgur.com/pCEoGjF.jpg'))  # image/jpeg
print(get_content_type('https://i.imgur.com/kJNdeQv.jpg'))  # image/gif
相关问题