python - 运行代码时出现 PIL unidentified Image 错误
问题描述
我正在学习有关网络抓取的课程,尝试运行以下代码,该代码旨在搜索 bing 图像中的术语并将所有图像保存到文件夹 scrapedimages
import requests
from bs4 import BeautifulSoup
from io import BytesIO
from PIL import Image
search = input("Enter the term you want to search:")
params = {"q": search}
r = requests.get("https://www.bing.com/images/search", params=params)
soup = BeautifulSoup(r.text, 'html.parser')
links = soup.findAll('a', {'class':'thumb'})
for item in links:
img_obj = requests.get(item.attrs["href"])
print("Getting image from:",img_obj)
title = item.attrs['href'].split('/')[-1]
Img = Image.open(BytesIO(img_obj.content))
Img.save("./scrapedimages/"+title, Img.format)
但是,当我的搜索词是“披萨”时,我收到以下错误
Traceback (most recent call last):
File "/home/dilan-sheth/PycharmProjects/Udemy/WebScrapery/images.py", line 45, in <module>
Img = Image.open(BytesIO(img_obj.content))
File "/home/dilan-sheth/PycharmProjects/Udemy/WebScrapery/venv/lib/python3.8/site-packages/PIL/Image.py", line 2930, in open
raise UnidentifiedImageError(
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f9654ada7c0>
发生这种情况有什么原因吗?
解决方案
UnidentifiedImageError
当您使用PIL.Image
访问 0KBs 的图像或不是图像的文件时会发生这种情况。
因此,您尝试访问Image.open
的内容很可能是 0KB 的图像或未requests.get(item.attrs["href"]).content
返回有效的图像文件。后来似乎是您的代码中的情况。希望它有所帮助!
推荐阅读
- javascript - HTA中的Javascript单选选项多个值
- jquery - 如何更改 JQuery Datatable 中的行颜色
- java - Java方法返回内存地址
- google-apps-script - 使用 Apps 脚本从 CSV 列表创建单元内下拉列表(Google 表格数据验证)
- ios - 防止 UIViewController 在模态旋转时旋转
- javascript - 如果选中复选框,如何添加元素,如果未选中,如何删除它?
- javascript - 如何手动使用量角器 ExpectedCondition?
- entity-framework - 计算 EF Core 中的外键表行数
- polymer - 如何使用 polymer-cli 安装 Polymer 1.x 模板
- css - WordPress 更改活动选项卡文本颜色和标题高度