csv - Python Scrapy : How to get CSVItemExporter to write columns in a specific order

标签 csv scrapy

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

谢谢。

最佳答案

这与Modifiying CSV export in scrapy有关

问题是导出器是在没有任何关键字参数的情况下实例化的,因此忽略了 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',
]

关于csv - Python Scrapy : How to get CSVItemExporter to write columns in a specific order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6943778/

相关文章:

python - Python中的json到csv转换返回单行?

csv - 使用 sed 填充 CSV 中的空白字段

python - 如何将管道分隔的文本文件转换为 CSV?

python - 如何使用sql读取csv

linux - 如何创建脚本以将 sed 命令添加到文件中(bash 脚本)

抓取文本编码

python - 使用 Scrapy 抓取网站时使用 Xpath 的混淆

python - 反复安装 scrapy 和 lxml 失败

python - 使用 Scrapy 从文本文件中的多个 URL 中抓取所有外部链接

scrapy - 如何在项目获取空字段时重试请求 n 次?