Python PIL:IOError:无法识别图像文件

use*_*003 5 python python-imaging-library

我想从以下网址获取图片:

image_url = http://www.eatwell101.com/wp-content/uploads/2012/11/Potato-Pancakes-recipe.jpg?b14316
Run Code Online (Sandbox Code Playgroud)

当我在浏览器中导航到它时,它确实看起来像一个图像.但是当我尝试时出现错误:

import urllib, cStringIO, PIL
from PIL import Image

img_file = cStringIO.StringIO(urllib.urlopen(image_url).read())   
image = Image.open(img_file)
Run Code Online (Sandbox Code Playgroud)

IOError:无法识别图像文件

我用这种方式复制了数百张图片,所以我不确定这里有什么特别之处.我能得到这张照片吗?

小智 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'
Run Code Online (Sandbox Code Playgroud)

使用用户代理标头将解决该问题。

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)
Run Code Online (Sandbox Code Playgroud)