栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何创建自定义的Scrapy项导出器?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何创建自定义的Scrapy项导出器?

确实,Scrapy文档没有明确说明放置项目导出器的位置。要使用项目导出器,请按照以下步骤操作。

  1. 选择一个Item Exporter类并将其导入到
    pipeline.py
    项目目录中。它可以是预定义的Item Exporter(例如
    XmlItemExporter
    ),也可以是用户定义的(如
    FanItemExporter
    问题中定义的)
  2. 在中创建Item Pipeline类
    pipeline.py
    。在此类中实例化导入的Item Exporter。详细信息将在答案的后面部分进行解释。
  3. 现在,在
    settings.py
    文件中注册该管道类。

以下是每个步骤的详细说明。该问题的解决方案包含在每个步骤中。

第1步

  • 如果使用预定义的Item Exporter类,则从

    scrapy.exporters
    模块导入它。
    例如:
    from scrapy.exporters import XmlItemExporter

  • 如果需要自定义导出器,请在文件中定义一个自定义类。我建议将类放在

    exporters.py
    文件中。放置在项目文件夹(这个文件
    settings.py
    items.py
    驻留)。

创建新的子类时,导入始终是一个好主意

baseItemExporter
。如果我们打算完全更改功能,那将是适当的。但是,在这个问题上,大多数功能都接近
JsonLinesItemExporter

因此,我将附加同一ItemExporter的两个版本。一个版本扩展了

baseItemExporter
类,另一个版本扩展了
JsonLinesItemExporter

版本1 :扩展

baseItemExporter

既然

baseItemExporter
是父类,
start_exporting()
finish_exporting()
export_item()
必须overrided,以满足我们的需要。

from scrapy.exporters import baseItemExporterfrom scrapy.utils.serialize import ScrapyJSonEnprerfrom scrapy.utils.python import to_bytesclass FanItemExporter(baseItemExporter):    def __init__(self, file, **kwargs):        self._configure(kwargs, dont_fail=True)        self.file = file        self.enprer = ScrapyJSonEnprer(**kwargs)        self.first_item = True    def start_exporting(self):        self.file.write(b'{'product': [')    def finish_exporting(self):        self.file.write(b'n]}')    def export_item(self, item):        if self.first_item: self.first_item = False        else: self.file.write(b',n')        itemdict = dict(self._get_serialized_fields(item))        self.file.write(to_bytes(self.enprer.enpre(itemdict)))

第2版 :扩展

JsonLinesItemExporter

JsonLinesItemExporter
提供与
export_item()
方法完全相同的实现。因此,仅
start_exporting()
finish_exporting()
方法被覆盖。

JsonLinesItemExporter
在文件夹中可以看到执行
python_dirpkgsscrapy-1.1.0-py35_0Libsite-packagesscrapyexporters.py

from scrapy.exporters import JsonItemExporterclass FanItemExporter(JsonItemExporter):    def __init__(self, file, **kwargs):        # To initialize the object using JsonItemExporter's constructor        super().__init__(file)    def start_exporting(self):        self.file.write(b'{'product': [')    def finish_exporting(self):        self.file.write(b'n]}')

注意 :将数据写入文件时,请务必注意,标准的Item
Exporter类需要二进制文件。因此,必须以二进制模式(

b
)打开文件。由于相同的原因,
write()
两个版本中的方法都将写入
bytes
文件。

第2步

创建一个Item Pipeline类。

from project_name.exporters import FanItemExporterclass FanExportPipeline(object):    def __init__(self, file_name):        # Storing output filename        self.file_name = file_name        # Creating a file handle and setting it to None        self.file_handle = None    @classmethod    def from_crawler(cls, crawler):        # getting the value of FILE_NAME field from settings.py        output_file_name = crawler.settings.get('FILE_NAME')        # cls() calls FanExportPipeline's constructor        # Returning a FanExportPipeline object        return cls(output_file_name)    def open_spider(self, spider):        print('Custom export opened')        # Opening file in binary-write mode        file = open(self.file_name, 'wb')        self.file_handle = file        # Creating a FanItemExporter object and initiating export        self.exporter = FanItemExporter(file)        self.exporter.start_exporting()    def close_spider(self, spider):        print('Custom Exporter closed')        # Ending the export to file from FanItemExport object        self.exporter.finish_exporting()        # Closing the opened output file        self.file_handle.close()    def process_item(self, item, spider):        # passing the item to FanItemExporter object for expoting to file        self.exporter.export_item(item)        return item

第三步

由于定义了“项目导出管道”,因此将该管道注册到

settings.py
文件中。还将字段添加
FILE_NAME
settings.py
文件。该字段包含输出文件的文件名。

将以下行添加到

settings.py
文件。

FILE_NAME = 'path/outputfile.ext'ITEM_PIPELINES = {    'project_name.pipelines.FanExportPipeline' : 600,}

如果

ITEM_PIPELINES
已经取消注释,则将以下行添加到
ITEM_PIPELINES
字典中。

'project_name.pipelines.FanExportPipeline' : 600,

这是创建自定义项目导出管道的一种方法。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/669152.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号