据我了解,为了让我使用文件管道,我需要将这些包含到我的 settings.py 中:
AWS_ACCESS_KEY_ID = 'access key'
AWS_SECRET_ACCESS_KEY= 'secret'
FILES_STORE = 's3://bucket/'
我需要将这些添加到我的 Item 对象中
file_urls = scrapy.Field()
files = scrapy.Field()
结果会是这样的:
{'file_urls': ['http://i.stack.imgur.com/tKsDb.png',
'http://i.stack.imgur.com/NAGkl.png'],
'files': [{'checksum': 'b0974ea6c88740bed353206b279e0827',
'path': 'full/762f5682798c5854833316fa171c71166e284630.jpg',
'url': 'http://i.stack.imgur.com/tKsDb.png'},
{'checksum': '9a42f7bd1dc45840312fd49cd08e6a5c',
'path': 'full/615eabb7b61e79b96ea1ddb34a2ef55c8e0f7ec3.jpg',
'url': 'http://i.stack.imgur.com/NAGkl.png'}]}
据我了解,文件管道将自动填充图像字段。
我的问题是,我是否可以更改图像字段中的“路径”值?在我的例子中,我想将许多不同的项目分别存储在不同的子目录下,并且它们都被同一个蜘蛛抓取,有没有办法可以做到这一点,例如创建和扩展我自己的文件管道?如果是这样,我将如何处理?
另外我需要提到的是,我为 1 个项目传递了 2 个不同的 URL,我希望它们位于不同的目录中
(是的,我知道它们是图像,我只是将其用作示例,因为它们是我首先找到的)
请您参考如下方法:
是的,这是可能的,如果您查看 scrapy 文件管道的源代码 here
你会看到它有你可以覆盖的方法,其中之一是 file_path 方法,你可以像这样将它添加到你的管道类中来覆盖它
def file_path(self, request, response=None, info=None):
# start of deprecation warning block (can be removed in the future)
def _warn():
from scrapy.exceptions import ScrapyDeprecationWarning
import warnings
warnings.warn('FilesPipeline.file_key(url) method is deprecated,\
please use file_path(request, response=None, info=None) instead',
category=ScrapyDeprecationWarning, stacklevel=1)
# check if called from file_key with url as first argument
if not isinstance(request, Request):
_warn()
url = request
else:
url = request.url
# detect if file_key() method has been overridden
if not hasattr(self.file_key, '_base'):
_warn()
return self.file_key(url)
# end of deprecation warning block
# Modify the file path HERE to your own custom path
filename = request.meta['filename']
media_ext = 'jpg'
return '%s/%s/%s.%s' % \
(request.meta['image_category'],
request.meta['image_month'],
filename, media_ext)
这样的结果将是一个像这样的目录:
vehicles/june/toyota.jpg
Where vehicles is the image_category, june is image_month and toyota is the filename
如果您查看代码的最后几行[这是我添加的唯一代码,其余代码是因为该方法来自 Scrapy 源代码]
# Modify the file path HERE to your own custom path
filename = request.meta['filename']
media_ext = 'jpg'
return '%s/%s/%s.%s' % \
(request.meta['image_category'],
request.meta['image_month'],
filename, media_ext)
返回自定义路径 现在这条路径取决于一些东西,在蜘蛛上你可以收集图像元字段,比如图像名称的文件名、图像类别和其他任何东西,比如图像拍摄日期,并在管道中使用它来创建自定义目录
