有没有办法使用scrapy将报废的每个项目导出到单独的json文件中?

时间:2015-05-13 08:28:39

标签: web-scraping scrapy scrapy-spider

目前我正在使用"产品"在我刮掉的每个项目之后,虽然它在一个Json文件中提供了所有项目。

1 个答案:

答案 0 :(得分:1)

您可以使用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

通过

pipeline中启用settings.py
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
相关问题