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的方式,就像您对任何其他类所做的那样,但它没有文档记录,我在我检查过的任何地方(谷歌、StackOverflow)都没有看到如何在Scrapy中做到这一点的示例。是否可能/是否支持,以及如何声明它们?
发布于 2019-02-04 19:41:01
是否可能/是否支持,以及如何声明它们?
这是可能的。具体采用哪种方式取决于您所共享的逻辑类型。
你可以用一种与剪贴画无关的方式来声明你的方法,也就是像你对任何其他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))或者,根据某些爬行器共享的函数中的实际逻辑,传递给add_*方法的简单processor可能是可行的。
发布于 2021-06-24 17:16:12
您可以在定义CustomItemLoader项的items.py文件中定义Product类,如下所示:
from scrapy import Item, Field
from scrapy.loader import ItemLoader
from scrapy.loader.processors import MapCompose, TakeFirst
class CustomItemLoader(ItemLoader):
default_output_processor = TakeFirst()
def custom_function(argument1, argument2, argument3):
# your custom function logic goes here..
pass
class Product(Item):
# define the fields for your item here like:
pass然后,您可以在爬行器代码中使用CustomItemLoader。如下所示:
from <PROJECT-NAME>.items import CustomItemLoader, Product
class MySpider(BaseSpiderName):
def parse_item(self, response):
product = CustomItemLoader(item=Product(), response=response)
product.custom_function(argument, ..., ...)https://stackoverflow.com/questions/54493641
复制相似问题