【问题标题】:Python Scrapy: How to get CSVItemExporter to write columns in a specific orderPython Scrapy:如何让 CSVItemExporter 以特定顺序写入列
【发布时间】:2011-08-04 15:03:59
【问题描述】:

在 Scrapy 中,我在 items.py 中以特定顺序指定了我的项目,并且我的蜘蛛再次以相同的顺序拥有这些项目。但是,当我运行蜘蛛并将结果另存为 csv 时,不会维护 items.py 或蜘蛛的列顺序。如何让 CSV 以特定顺序显示列。示例代码将不胜感激。

谢谢。

【问题讨论】:

    标签: csv scrapy


    【解决方案1】:

    这与Modifiying CSV export in scrapy有关

    问题是exporter实例化时没有任何关键字参数,所以像EXPORT_FIELDS这样的关键字被忽略了。解决方法是一样的:你需要子类化 CSV 项目导出器来传递关键字参数。

    按照上面的方法,我创建了一个新文件 xyzzy/feedexport.py(将“xyzzy”更改为你的 scrapy 类的名称):

    """
    The standard CSVItemExporter class does not pass the kwargs through to the
    CSV writer, resulting in EXPORT_FIELDS and EXPORT_ENCODING being ignored
    (EXPORT_EMPTY is not used by CSV).
    """
    
    from scrapy.conf import settings
    from scrapy.contrib.exporter import CsvItemExporter
    
    class CSVkwItemExporter(CsvItemExporter):
    
        def __init__(self, *args, **kwargs):
            kwargs['fields_to_export'] = settings.getlist('EXPORT_FIELDS') or None
            kwargs['encoding'] = settings.get('EXPORT_ENCODING', 'utf-8')
    
            super(CSVkwItemExporter, self).__init__(*args, **kwargs)
    

    然后将其添加到 xyzzy/settings.py 中:

    FEED_EXPORTERS = {
        'csv': 'xyzzy.feedexport.CSVkwItemExporter'
    }
    

    现在 CSV 导出器将支持 EXPORT_FIELD 设置 - 也添加到 xyzzy/settings.py:

    # By specifying the fields to export, the CSV export honors the order
    # rather than using a random order.
    EXPORT_FIELDS = [
        'field1',
        'field2',
        'field3',
    ]
    

    【讨论】:

    • 我看到这篇文章已经很老了。是否在最近的版本中以更简单的方式解决了这个问题?
    • 请在你的回答中解决这个问题from scrapy.exporters import CsvItemExporter
    • @HozayfaElRifai 谢谢,from scrapy.contrib.exporter import CsvItemExporte' 应该是 from scrapy.exporters import CsvItemExporter
    【解决方案2】:

    我不知道你问问题的时间,但 Scrapy 现在为 BaseItemExporter 类提供了一个 fields_to_export 属性,CsvItemExporter 继承。 根据 0.22 版:

    fields_to_export

    包含将导出的字段名称的列表,如果要导出所有字段,则为 None。默认为无。

    一些出口商(如 CsvItemExporter)遵守订单 此属性中定义的字段。

    另请参阅 Scrapy 网站上 BaseItemExporterCsvItemExporter 的文档。

    不过,为了使用此功能,您必须创建自己的 ItemPipeline,详见this answer

    【讨论】:

      猜你喜欢
      • 2018-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      相关资源
      最近更新 更多