Python 刮痧';为CSViteExporter设置自定义CSV头

Python 刮痧';为CSViteExporter设置自定义CSV头,python,python-3.x,scrapy,Python,Python 3.x,Scrapy,我正在尝试解析XML并将其转换为CSV。棘手的部分是,标题应该与第三方CSV解析器文档中指定的术语完全匹配,并且在单词之间包含空格,即“项目标题”、“项目描述”等 由于Items.py中将项定义为变量,因此我无法创建包含空格的项,即 Item title=scrapy.Field() 我已尝试添加到settings.py: FEED\u EXPORT\u字段=[“项目标题”、“项目描述”] 它编辑CVS标题,但在此之后,它不再匹配项,因此不会将任何数据填充到.csv中 类MySpider(X

我正在尝试解析XML并将其转换为CSV。棘手的部分是,标题应该与第三方CSV解析器文档中指定的术语完全匹配,并且在单词之间包含空格,即“项目标题”、“项目描述”等

由于Items.py中将项定义为变量,因此我无法创建包含空格的项,即

Item title=scrapy.Field()
我已尝试添加到settings.py:

FEED\u EXPORT\u字段=[“项目标题”、“项目描述”]
它编辑CVS标题,但在此之后,它不再匹配项,因此不会将任何数据填充到.csv中

类MySpider(XMLFeedSpider): 名称='示例' 允许的_域=['example.com'] 起始URL=['http://example.com/feed.xml'] itertag='item' def parse_节点(自身、响应、节点): item=FeedItem() item['id']=node.xpath('/*[name()=“g:id”]/text()).get() item['title']=node.xpath('//*[name()=“g:title”]/text()).get() item['description']=node.xpath('//*[name()=“g:description”]/text()).get() 退货项目 解析器工作正常,我得到了所需的所有数据。问题在于csv标题

有没有一种方法可以轻松添加与项目名称不匹配且包含很少单词的自定义标题

我当前获得的输出:

id, title, description
12345, Lorem Ipsum, Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
12346, Quick Fox, The quick brown fox jumps over the lazy dog.
所需的输出应如下所示:

ID, Item title, Item description
12345, Lorem Ipsum, Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
12346, Quick Fox, The quick brown fox jumps over the lazy dog.
测试输入:


例子
http://www.example.com
Example.com的说明
12345
乱数假文
知识是一种美德,是一种美德,是一种美德,是一种美德。但是,在最低限度上,我们需要一个实验室来进行日常工作。
12346
敏捷的狐狸
敏捷的棕色狐狸跳过了懒狗。
这是items.py的内容:

import scrapy
类别饲料项目(刮痕项目):
id=scrapy.Field()
title=scrapy.Field()
description=scrapy.Field()
通过

您可以使用内置字典
dict
键入作为项,并将所需的csv标题值作为字典键:

    def parse_node(self, response, node):
        item = dict() #item = {}
        item['ID'] = node.xpath('//*[name()="g:id"]/text()').get()
        item['Item title'] = node.xpath('//*[name()="g:title"]/text()').get()
        item['Item description'] = node.xpath('//*[name()="g:description"]/text()').get()

        return item #yield item

您可以制作自己的csv导出器!理想情况下,您可以使用不同的方法扩展当前导出器:

# exporters.py 
from scrapy.exporters import CsvItemExporter

class MyCsvItemExporter(CsvItemExporter):
    header_map = {
        'description': 'Item Description',
    }

    def _write_headers_and_set_fields_to_export(self, item):
        if not self.include_headers_line:
            return
        # this is the parent logic taken from parent class
        if not self.fields_to_export:
            if isinstance(item, dict):
                # for dicts try using fields of the first item
                self.fields_to_export = list(item.keys())
            else:
                # use fields declared in Item
                self.fields_to_export = list(item.fields.keys())
        headers = list(self._build_row(self.fields_to_export))

        # here we add our own extra mapping
        # map headers to our value
        headers = [self.header_map.get(header, header) for header in headers]
        self.csv_writer.writerow(headers)
然后在您的设置中激活它:

FEED_EXPORTERS = {
    'csv': 'myproject.exporters.MyCsvItemExporter',
}

嗨,linksmai,你能提供一些输入数据和想要的输出吗?@Dylan_w,当然。我已经用期望的输出和输入更新了我的问题。谢谢!工作非常完美,只需在(CsvItemExporter)之后添加冒号:
python类MyCsvItemExporter(CsvItemExporter):