假设我有一个像这样的 imgur 网址:https ://imgur.com/pCEoGjF
从网址我不知道这是图片还是gif。我知道我可以在文件末尾添加“.jpg”以获得图像的直接链接,但如果链接恰好是 gif,这也会显示 gif。我将如何以编程方式(使用 imgur API 或其他方式)检查 url https://imgur.com/pCEoGjF或https://imgur.com/pCEoGjF.jpg 上的项目是图像还是 gif?
编辑:我试过这个
print(requests.head(submission.url + ".jpg").headers['Content-Type'])
Run Code Online (Sandbox Code Playgroud)
但它抱怨以下错误:
KeyError: 'content-type'
Run Code Online (Sandbox Code Playgroud)
暗示内容类型不是标题中的键。我打印了标题并确认了这一点,因为它们如下:
{'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'}
Run Code Online (Sandbox Code Playgroud)
我想我可以检查 content-length 是否不为 0 以查看它是否是 gif?想法?
使用requests库:
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
Run Code Online (Sandbox Code Playgroud)