image - 如何验证此 URL 重定向到图像?

标签 image python-2.7 encoding

我正在开发一项用 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&amp;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/

相关文章:

javascript - 为什么href属性使用url编码而不是html编码?

html - 带有图像和文本的链接 - 组合还是单独?

python - 如何在 python numpy 中从周围的白色背景中裁剪对象?

java - PaintComponent 未被调用 - Java

python - 当其中一行匹配条件时如何返回数据库实体的总计数

python - 从不包括管道的脚本运行 scrapy

python - 图像自适应阈值处理导致数据丢失

python - sqlalchemy 使列遵循规则的关系

ruby - 从 Ruby 中的 UTF-16 编码文件中读取内容

mysql - 将 LZW 编码数据保存到 mySQL 数据库中