如何使用我自己的自定义文件名存储文件?
如果我的自定义文件名需要包含同一项目中的另一个抓取字段,该怎么办?例如,使用item['desc']和和图像的文件名item['image_url']。如果我理解正确,那将涉及以某种方式从图像管道访问其他项目字段。
item['desc']
item['image_url']
任何帮助将不胜感激。
这就是我在Scrapy 0.10中解决问题的方式。检查FSImagesStoreChangeableDirectory的persist_image方法。下载图像的文件名是密钥
class FSImagesStoreChangeableDirectory(FSImagesStore): def persist_image(self, key, image, buf, info,append_path): absolute_path = self._get_filesystem_path(append_path+'/'+key) self._mkdir(os.path.dirname(absolute_path), info) image.save(absolute_path) class ProjectPipeline(ImagesPipeline): def __init__(self): super(ImagesPipeline, self).__init__() store_uri = settings.IMAGES_STORE if not store_uri: raise NotConfigured self.store = FSImagesStoreChangeableDirectory(store_uri)
这只是对scrapy 0.24(EDITED)答案的实现,其中image_key()不推荐使用
image_key()
class MyImagesPipeline(ImagesPipeline): #Name download version def file_path(self, request, response=None, info=None): #item=request.meta['item'] # Like this you can use all from item, not just url. image_guid = request.url.split('/')[-1] return 'full/%s' % (image_guid) #Name thumbnail version def thumb_path(self, request, thumb_id, response=None, info=None): image_guid = thumb_id + response.url.split('/')[-1] return 'thumbs/%s/%s.jpg' % (thumb_id, image_guid) def get_media_requests(self, item, info): #yield Request(item['images']) # Adding meta. Dunno how to put it in one line :-) for image in item['images']: yield Request(image)