该Scrapy文档列出所有the built-in methods of ItemLoader instances并解释how to declare your own Item Loaders。不过,声明任何ItemLoaders将适用于所有加工项目。您可以修改自己的行为有点与Item Loader Contexts,而这往往是粒度不够。
假设我有一个Scrapy项目中,蜘蛛和项目都继承了相同的基本蜘蛛和项目装载机,但蜘蛛都包含特定于站点的逻辑与常用功能屈指可数。无处Scrapy文档中才能找到添加类方法来ItemLoaders提及,这样的代替:
import mymodule
class MySpider(BaseSpiderName):
def parse_item(self, response):
product = ItemLoader(item=Product(), response=response)
new_value = mymodule.myfunction(argument, ..., ...)
product.add_value('my_field', new_value)
你可以写:
# (no extra import)
class MySpider(BaseSpiderName):
def parse_item(self, response):
product = CustomItemLoader(item=Product(), response=response)
product.custom_function(argument, ..., ...)
尽管这似乎是一个明显的方法来扩展ItemLoaders就像你会为任何其他的类,它没有记录,我没有看到如何做到这一点在任何地方Scrapy我已经检查(谷歌,StackOverflow的)例子。是否有可能/支持,你会怎么申报呢?
是否有可能/支持,你会怎么申报呢?
有可能的。哪种方式做到这一点取决于逻辑的要共享的类型。
您可以在Scrapy无关的方式宣告你的方法,即,你会与任何其他Python类做:继承你的CustomItemLoader
类,并定义在子类中的方法:
from scrapy.loaders import ItemLoader
class CustomItemLoader(ItemLoader):
def custom_function(self, *args, **kwargs):
self.add_value('my_field', mymodule.myfunction(*args, **kwargs))
另外,根据您的一些蜘蛛共享该功能具有实际的逻辑,你传递给你的processor方法简单add_*
可能是要走的路。