Scrapy CSV 输出重复字段

Scrapy CSV output duplicates fields

我有一个蜘蛛(下图),我希望能够每 10 天左右通过 Cron 作业 运行 它,但是,每次我 运行 它都是在第一次之后.它重写了字段,而不是仅仅将项目附加到 CSV 中的适当字段。我怎样才能让我只有一组字段 headers 在顶部和它下面的所有数据,无论我 运行 它多少次?

import scrapy

class Wotd(scrapy.Item):
    word = scrapy.Field()
    definition = scrapy.Field()
    sentence = scrapy.Field()
    translation = scrapy.Field()


class WotdSpider(scrapy.Spider):
    name = 'wotd'
    allowed_domains = ['www.spanishdict.com/wordoftheday']
    start_urls = ['http://www.spanishdict.com/wordoftheday/']
    custom_settings = {
        #specifies exported fields and their order
    'FEED_EXPORT_FIELDS': ['word','definition','sentence','translation']
    }

def parse(self, response):
    jobs = response.xpath('//div[@class="sd-wotd-text"]')
    for job in jobs:
        item = Wotd()
        item['word'] = job.xpath('.//a[@class="sd-wotd-headword-link"]/text()').extract_first()
        item['definition'] = job.xpath('.//div[@class="sd-wotd-translation"]/text()').extract_first()
        item['sentence'] = job.xpath('.//div[@class="sd-wotd-example-source"]/text()').extract_first()
        item['translation'] = job.xpath('.//div[@class="sd-wotd-example-translation"]/text()').extract_first()
        yield item 

根据我在 Scrapy 文档上阅读的内容,看起来我可能不得不弄乱 CsvItemExporter class 并设置 include_headers_line=False 但我不确定在哪里添加它class 在项目结构中。

首先,您没有分享您当前的项目结构,因此很难建议将其放在具体示例中的什么位置。

假设您的项目名为 my_project。在主项目目录(包含 settings.py 的目录)下,创建文件 exporters.py 内容如下:

import scrapy.exporters

class NoHeaderCsvItemExporter(scrapy.exporters.CsvItemExporter):
    def __init__(self, file, join_multivalued=', ', **kwargs):
        super(NoHeaderCsvItemExporter, self).__init__(file=file, include_headers_line=False, join_multivalued=join_multivalued, **kwargs)

Class NoHeaderCsvItemExporter 继承自标准 CSV 导出器,只是指定我们不希望输出中包含 header 行。

接下来,您必须在 settings.py 或蜘蛛 custom_settings 中为 CSV 格式指定新的导出器 class。按照您当前使用后一个选项的方法,它将是:

custom_settings = {
    'FEED_EXPORT_FIELDS': ['word','definition','sentence','translation'],
    'FEED_EXPORTERS': {
        'csv': 'my_project.exporters.NoHeaderCsvItemExporter',
    }
}

请注意,使用此 class,CSV 中不会包含 任何 header 行,即使是第一次导出也不行.