如何解决使用Scrapy保存.svg图像
我正在使用Scrapy,我想将网页中的某些.svg图像保存在本地计算机上。这些图片的网址结构为'__。com / svg / 4/8/3 / 1425.svg'(并且是完整的工作网址,包括https)。
我已经在我的items.py文件中定义了该项目:
class ImageItem(scrapy.Item):
image_urls = scrapy.Field()
images = scrapy.Field()
我已在我的设置中添加了以下内容:
ITEM_PIPELINES = {
'scrapy.pipelines.images.ImagesPipeline': 1,}
IMAGES_STORE = '../Data/Silks'
MEDIA_ALLOW_REDIRECTS = True
在主要的解析函数中,我调用:
imageItem = ImageItem()
imageItem['image_urls'] = [url]
yield imageItem
但是它不会保存图像。 Ive遵循了文档,并尝试了许多事情,但始终出现以下错误:
StopIteration: <200 https://www.________.com/svg/4/8/3/1425.svg>
During handling of the above exception,another exception occurred:
......
......
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x1139233b0>
我错过了什么吗?有人可以帮忙吗?我完全陷入了困境。
解决方法
Gallaecio是对的! Scrapy的.svg文件类型有问题。将imagePipeline更改为filePipeline,它可以正常工作!
对于陷入困境的任何人,文档为here
,ImagesPipeline
使用的 Python 图像库 (PIL) 不支持矢量图像。
如果您仍想从 ImagesPipeline
功能中受益而不是切换到更通用的 FilesPipeline
,您可以按照这些方式做一些事情
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPM
from io import BytesIO
class SvgCompatibleImagesPipeline(ImagesPipeline):
def get_images(self,response,request,info,*,item=None):
"""
Add processing of SVG images to the standard images pipeline
"""
if isinstance(response,scrapy.http.TextResponse) and response.text.startswith('<svg'):
b = BytesIO()
renderPM.drawToFile(svg2rlg(BytesIO(response.body)),b,fmt='PNG')
res = response.replace(body=b.getvalue())
else:
res = response
return super().get_images(res,item=item)
这会将响应正文中的 SVG 图像替换为其 PNG 版本,可以由常规 ImagesPipeline
进一步处理。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。