2013-06-18 17 views
5

を識別することができない私は、次のURLから画像を取得しようとしています:私は、ブラウザでそれに移動するとPythonのPIL:例外IOError:画像ファイル

image_url = http://www.eatwell101.com/wp-content/uploads/2012/11/Potato-Pancakes-recipe.jpg?b14316 

、それは確かに画像のように見えます。画像の

import urllib, cStringIO, PIL 
from PIL import Image 

img_file = cStringIO.StringIO(urllib.urlopen(image_url).read()) 
image = Image.open(img_file) 

IOError: cannot identify image file

私がコピーした数百人をこのように、私はここで特別なのかわからないんだけど:しかし、私は、私がしようとするとエラーが発生します。この画像を入手できますか?

答えて

3

問題は、画像内に存在しません。

>>> urllib.urlopen(image_url).read() 
'\n<?xml version="1.0" encoding="utf-8"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n<html>\n <head>\n <title>403 You are banned from this site. Please contact via a different client configuration if you believe that this is a mistake.</title>\n </head>\n <body>\n <h1>Error 403 You are banned from this site. Please contact via a different client configuration if you believe that this is a mistake.</h1>\n <p>You are banned from this site. Please contact via a different client configuration if you believe that this is a mistake.</p>\n <h3>Guru Meditation:</h3>\n <p>XID: 1806024796</p>\n <hr>\n <p>Varnish cache server</p>\n </body>\n</html>\n' 

user agent headerを使用すると問題が解決されます。

opener = urllib2.build_opener() 
opener.addheaders = [('User-agent', 'Mozilla/5.0')] 
response = opener.open(image_url) 
img_file = cStringIO.StringIO(response.read()) 
image = Image.open(img_file) 
+0

魅力的なように働いた。 – user984003

+0

このhederは他のイメージでも必要でした:( 'Accept'、 'text/html、application/xhtml + xml、application/xml; q = 0.9、*/*; q = 0.8') – user984003

4

私は

In [3]: f = urllib.urlopen('http://www.eatwell101.com/wp-content/uploads/2012/11/Potato-Pancakes-recipe.jpg') 

In [9]: f.code 
Out[9]: 403 

を使用してファイルを開いたときに、このイメージを返していません。

ユーザーエージェントのヘッダーを指定して、サーバーがブラウザであると思うようにすることができます。 (ヘッダ情報を送信することが容易であるため)requestsライブラリを使用して

In [7]: f = requests.get('http://www.eatwell101.com/wp-content/uploads/2012/11/Potato-Pancakes-recipe.jpg', headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:16.0) Gecko/20100101 Firefox/16.0,gzip(gfe)'}) 
In [8]: f.status_code 
Out[8]: 200 
2

イメージを取得するには、まずイメージを保存してからPILにロードします。例えば:

import urllib2,PIL 

opener = urllib2.build_opener(urllib2.HTTPRedirectHandler(), urllib2.HTTPCookieProcessor()) 
image_content = opener.open("http://www.eatwell101.com/wp-content/uploads/2012/11/Potato-Pancakes-recipe.jpg?b14316").read() 
opener.close() 

save_dir = r"/some/folder/to/save/image.jpg" 
f = open(save_dir,'wb') 
f.write(image_content) 
f.close() 

image = Image.open(save_dir) 
... 
+1

バイナリモード 'b'を忘れる – ghanbari

関連する問題