Python Scrapy:如何让CSVItemExporter按特定顺序写入列

use*_*190 12 csv scrapy

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

谢谢.

小智 18

这与scrapy中的Modifiying CSV导出有关

问题是导出器实例化时没有任何关键字参数,因此忽略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)
Run Code Online (Sandbox Code Playgroud)

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

FEED_EXPORTERS = {
    'csv': 'xyzzy.feedexport.CSVkwItemExporter'
}
Run Code Online (Sandbox Code Playgroud)

现在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',
]
Run Code Online (Sandbox Code Playgroud)

  • 我看到这篇文章已经很老了.在最近的版本中,此问题是否已以更简单的方式得到解决? (3认同)

小智 6

我不知道您提出问题的时间,但Scrapy现在为BaseItemExporter类提供了fields_to_export属性,CsvItemExporter继承了该属性.根据版本0.22:

fields_to_export

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

某些导出器(如CsvItemExporter)遵循此属性中定义的字段的顺序.

另见文档BaseItemExporterCsvItemExporter的Scrapy网站上.

但是,要使用此功能,您必须创建自己的ItemPipeline,如本答案中所述