You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PIL库运行报NameError: name 'PIL' is not defined错误如何解决?

问题根因

两个NameError报错是Python命名空间导入规则导致的:
你使用了from PIL import Image, UnidentifiedImageError的导入写法,只会把Image、UnidentifiedImageError这两个名称导入到当前文件的全局命名空间,PIL这个顶级包名并没有被导入到当前作用域,所以代码里直接写PIL.Image、PIL.UnidentifiedImageError都会触发未定义错误。

修复方案

方式1:直接使用已导入的名称(最简便)

把代码里的PIL.Image改成Image,PIL.UnidentifiedImageError改成UnidentifiedImageError即可,修改后的完整代码如下:

from bs4 import BeautifulSoup
import requests
from PIL import Image, UnidentifiedImageError
from io import BytesIO
import os

# 提前创建存储目录避免写入时报错
os.makedirs("./scraped_images", exist_ok=True)

search = input("Enter: ")
params = {"q": search}
url = "https://www.bing.com/images/search"
r = requests.get(url, params=params)

soup = BeautifulSoup(r.text, "html.parser")
links = soup.findAll("a", {"class": "iusc"})

for item in links:
    img_obj = requests.get("https://www.bing.com"+item.attrs["href"])
    title = item.attrs["href"].split("/")[-1]
    try:
        # 去掉前缀PIL.
        img = Image.open(BytesIO(img_obj.content))
        img.save("./scraped_images/" + title, img.format)
    # 去掉前缀PIL.
    except UnidentifiedImageError: 
        print(f"无法识别的图片资源:{item}")

方式2:导入PIL顶级包

如果要保留PIL.前缀的写法,只需要在导入部分新增一行import PIL即可:

import PIL # 新增此行导入顶级包
from bs4 import BeautifulSoup
import requests
from PIL import Image, UnidentifiedImageError
from io import BytesIO

UnidentifiedImageError相关说明

这个错误是Pillow识别不了请求返回的内容为合法图片时抛出的,属于预期内的业务异常,必须显式捕获处理,常见触发原因包括:

  • 请求返回的不是图片资源,而是网页、404错误页等
  • 图片资源损坏、格式不被Pillow支持
  • 请求被反爬拦截,返回了加密内容或验证页

保持现有捕获逻辑即可,捕获后可直接跳过无效资源继续爬取下一个。

内容的提问来源于stack exchange,提问作者codeiscool

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 15:36:05