无法识别图像文件 %r" % (filename if filename else fp)

cannot identify image file %r" % (filename if filename else fp)

我正在尝试使用 PIL 下载图像,但它显示 UnidentifiedImageError

d = login_session.get("https://example.com/xyz.php")
d = Image.open(BytesIO(d.content))
d.save("xyz.png")

这里我需要先登录一个站点,然后再下载一张图片,为此,我使用了login_session来创建一个session

  File "C:/Users/dx4io/OneDrive/Desktop/test.py", line 21, in <module>
    captcha = Image.open(BytesIO(captcha.content))
  File "C:\Users\dx4io\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 3024, in open
    "cannot identify image file %r" % (filename if filename else fp)
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x000001A5E1B5AEB8>

问题是您尝试访问的页面没有 return 图片。例如,包含 return 个图像的页面是 https://www.google.com/favicon.ico, but google searching for image returns an html page: https://www.google.com/search?q=image

为了测试,我们可以尝试从不是图像的页面获取图像。

from io import BytesIO
from PIL import Image
import requests

notanimage='https://www.google.com/search?q=image'
yesanimage="https://www.google.com/favicon.ico"

现在 运行 此代码有效:

d = requests.get(yesanimage)
d = Image.open(BytesIO(d.content))
d.save("xyz.png")

但这给出了 UnidentifiedImageError:

d = requests.get(notanimage)
d = Image.open(BytesIO(d.content))
d.save("xyz.png")

此代码运行无误:

from io import BytesIO
from PIL import Image
import requests
d = requests.get("https://defendtheweb.net/extras/playground/captcha/captcha1.php")
d = Image.open(BytesIO(d.content))
d.save("xyz.png")