首页 > 解决方案 > 用scrapy爬取后如何关闭json文件的写入?

问题描述

我通过从 CLI 调用它来爬取 scrapy 1.5.1:

scrapy crawl test -o data/20181204_test.json -t json 

我的管道非常简单,我在其中处理项目,处理后我想将其拉入 close_spider 方法中的 zip 存档中:

class BidPipeline(object):
    def process_item(self, item, spider):
        return item
    def close_spider(self, spider):
        # trying to close the writing of the file
        self.exporter.finish_exporting()
        self.file.close()
        # zip the img and json files into an archive
        cleanup('test')

清理方法:

def cleanup(name):
    # create zip archive with all images inside
    filename = '../zip/' + datetime.datetime.now().strftime ("%Y%m%d-%H%M") + '_' + name
    imagefolder = 'full'
    imagepath = '/Users/user/test_crawl/bid/images'
    shutil.make_archive(
        filename, 
        'zip', 
        imagepath,
        imagefolder
    ) 
    # delete images
    shutil.rmtree(imagepath+ '/' + imagefolder)

    # add csv file to  zip archive
    filename_zip = filename + '.zip'
    zip = zipfile.ZipFile(filename_zip,'a') 
    path_to_file = '/Users/user/test_crawl/bid/data/'+  datetime.datetime.now().strftime ("%Y%m%d") + '_' + name + '.json'
    zip.write(path_to_file, os.path.basename(path_to_file)) 
    zip.close()

使用 self.file.close() 后的回溯:

AttributeError: 'BidPipeline' object has no attribute 'exporter'
2018-12-04 06:03:48 [scrapy.extensions.feedexport] INFO: Stored json feed (173 items) in: data/20181204_test.json

没有 file.close 就没有回溯错误,起初看起来还可以,但是 json 文件被截断了。

来自 zip 存档的解压缩文件的结尾以及来自 scrapy 的 json 文件输出:

..a46.jpg"]},

scrapy 输出的 json 文件:

a46.jpg"]}]

如何关闭文件的写入以压缩它?

标签: pythonscrapy

解决方案


尝试删除此行self.exporter.finish_exporting()

您的对象没有exporter属性。


推荐阅读