首页 > 解决方案 > json 文件在使用 python 放入 zip 存档时损坏

问题描述

用scrapy爬取一个站点后,我在关闭方法中创建了一个zip存档,将图片拉入其中。然后我将一个有效的 json 文件添加到存档中。

解压缩后(在 mac os x 或 ubuntu 上),json 文件将显示损坏。最后一项不见了。

解压文件结束:

..a46.jpg"]},

原始文件:

a46.jpg"]}]

代码:

# 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
) 

# add json 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()

我可以多次重现此错误,其他一切看起来都很好。

标签: pythonpython-3.xscrapy

解决方案


解决方案是使用 scrapy jsonitemexporter 而不是 fead exporter,因为 feed exporter 将在 close_spider() 期间写入文件,这已经很晚了。

这很容易完成。

在文件 pipelines.py 中加载 JsonItemExporter

from scrapy.exporters import JsonItemExporter

像这样更改您的管道:

class MyPipeline(object):

    file = None

    def open_spider(self, spider):
        self.file = open('data/test.json', 'wb')
        self.exporter = JsonItemExporter(self.file)
        self.exporter.start_exporting()

    def close_spider(self, spider):
        self.exporter.finish_exporting()
        self.file.close()
        cleanup('zip_method')

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

zip_method 包含问题中提到的邮政编码。


推荐阅读