只是想知道有没有办法可以检查网址是否链接到Django中的有效图片。
答案 0 :(得分:4)
>>> import requests
>>> from PIL import Image
>>> from StringIO import StringIO
>>> r = requests.get('http://cdn.sstatic.net/stackoverflow/img/sprites.png')
>>> im = Image.open(StringIO(r.content))
>>> im
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=238x1073 at 0x2845EA8>
答案 1 :(得分:3)
使用urllib2检查此问题的简单方法。
>>> import urllib2
>>> url = 'https://www.google.com.pk/images/srpr/logo3w.png'
>>> try:
... f = urllib2.urlopen(urllib2.Request(url))
... imageFound = True
... except:
... imageFound = False
...
>>> imageFound
True
答案 2 :(得分:3)
这是一种故障保护方法。 首先,解析网址以获取域名和其他域名。
>>> from urllib.parse import urlparse
>>> url = 'http://example.com/random/folder/path.html'
>>> parse_object = urlparse(url)
>>> parse_object.netloc
'example.com'
>>> parse_object.path
'/random/folder/path.html'
>>> parse_object.scheme
'http'
现在,使用以上信息获取内容类型。使用parse_object.netloc
代替sstatic.net,使用parse_object.path
代替硬编码路径。
>>> import httplib
>>> conn = httplib.HTTPConnection("sstatic.net")
>>> conn.request("HEAD", "/stackoverflow/img/favicon.ico")
>>> res = conn.getresponse()
>>> print res.getheaders()
[('content-length', '1150'), ('x-powered-by', 'ASP.NET'), ('accept-ranges', 'bytes'), ('last-modified', 'Mon, 02 Aug 2010 06:04:04 GMT'), ('etag', '"2187d82832cb1:0"'), ('cache-control', 'max-age=604800'), ('date', 'Sun, 12 Sep 2010 13:39:26 GMT'), ('content-type', 'image/x-icon')]
这告诉你它是1150字节的图像(image / * mime-type)。有足够的信息供您决定是否要获取完整资源。
修改强>
对于缩短的网址,例如http://goo.gl/IwruD
指向http://ubuntu.icafebusiness.com/images/ubuntugui2.jpg
,在您收到的回复中,还有一个名为'location'
的附加参数。
这就是我所说的:
>>> import httplib
>>> conn = httplib.HTTPConnection("goo.gl")
>>> conn.request("HEAD", "/IwruD")
>>> res = conn.getresponse()
>>> print res.getheaders()
[('x-xss-protection', '1; mode=block'),
('x-content-type-options', 'nosniff'),
('transfer-encoding', 'chunked'),
('age', '64'),
('expires', 'Mon, 01 Jan 1990 00:00:00 GMT'),
('server', 'GSE'),
('location', 'http://ubuntu.icafebusiness.com/images/ubuntugui2.jpg'),
('pragma', 'no-cache'),
('cache-control', 'no-cache, no-store, max-age=0, must-revalidate'),
('date', 'Sat, 30 Jun 2012 08:52:15 GMT'),
('x-frame-options', 'SAMEORIGIN'),
('content-type', 'text/html; charset=UTF-8')]
在直接网址中,你找不到它。
>>> import httplib
>>> conn = httplib.HTTPConnection("ubuntu.icafebusiness.com")
>>> conn.request("HEAD", "/images/ubuntugui2.jpg")
>>> res = conn.getresponse()
>>> print res.getheaders()
[('content-length', '78603'), ('accept-ranges', 'bytes'), ('server', 'Apache'), ('last-modified', 'Sat, 16 Aug 2008 01:36:17 GMT'), ('etag', '"1fb8277-1330b-45489c3ad2640"'), ('date', 'Sat, 30 Jun 2012 08:55:46 GMT'), ('content-type', 'image/jpeg')]
您可以使用简单的代码查找:
>>> r = res.getheaders()
>>> redirected = False
>>> for e in r:
>>> if(e[0] == 'location'):
>>> redirected = e
>>>
>>> if(redirected != False):
>>> print redirected[1]
'http://ubuntu.icafebusiness.com/images/ubuntugui2.jpg'