我正在开发一项用 Python 编写的服务,该服务有时会从给定的 URL 下载图像并将它们存储在服务器上。
此服务会检查从 URL 返回的内容类型,并且仅在内容类型为“image/jpeg”等时才下载图像。
我最近遇到了一个关于以下 URL 的有趣问题: http://www.nationaldentalreviews.org/Handlers/ImageDisplay.ashx?qUID=8597&qType=__ProfileMicroSite
此 URL 在浏览器中打开时会显示某种编码字符串。
当用作图像标签的“src”时,它会呈现图像。
<html>
<body>
<img src = 'http://www.nationaldentalreviews.org/Handlers/ImageDisplay.ashx?qUID=8597&qType=__ProfileMicroSite'>
</body>
</html>
这个URL的内容类型是text/html
在 Python 中,有什么方法可以让我识别此 URL 指向可用作“src”的图像吗?
最佳答案
使用内置的 imghdr
模块:
>>> import imghdr
>>> import urllib2
>>>
>>> url = 'http://www.nationaldentalreviews.org/Handlers/ImageDisplay.ashx?qUID=8597&qType=__ProfileMicroSite'
>>> data = urllib2.urlopen(url).read()
>>>
>>> imghdr.what(None, data)
'jpeg'
>>> # To show that it's only checking the header; don't do this though
>>> imghdr.what('', data:10])
'jpeg'
>>> imghdr.what('', 'CORRUPT_OR_NOT_AN_IMAGE' + data)
>>> # The last call returns None
>>>
关于image - 如何验证此 URL 重定向到图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31999859/