有没有办法使用 scrapy 将每个被抓取的项目导出到一个单独的 json 文件中?

Is there a way using scrapy to export each item that is scraped into a separate json file?

目前我在抓取每个项目后使用 "yield item",尽管它在一个 Json 文件中提供了所有项目。

您可以使用 scrapy-pipeline,然后您可以将每个 item 插入到单独的文件中。

我在我的爬虫中设置了一个 counter 以便它在每个项目产量上递增并将该值添加到 item。我正在使用该 counter 值创建文件名。

Test_spider.py

class TestSpider(Spider):
    # spider name and all
    file_counter = 0

def parse(self, response):
    # your code here

def parse_item(self, response):
     # your code here
     self.file_counter += 1
      item = Testtem(
        #other items, 
        counter=self.file_counter)
     yield item

通过

settings.py中启用pipeline
ITEM_PIPELINES = {'test1.pipelines.TestPipeline': 100}

pipelines.py

class TestPipeline(object):

    def process_item(self, item, spider):
        with open('test_data_%s' % item.get('counter'), 'w') as wr:
            item.pop('counter') # remove the counter data, you don't need this in your item
            wr.write(str(item))
        return item