python - 用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"]}]
如何关闭文件的写入以压缩它?
解决方案
尝试删除此行self.exporter.finish_exporting()
。
您的对象没有exporter
属性。
推荐阅读
- multithreading - AIX/xlclang++:thread_local 变量给出链接器错误:未定义符号
- kubernetes - 使用 Redis 处理程序在 Istio 中进行速率限制
- c# - 用于特定扩展验证的 RegEx
- c# - 如何使用方法将对象添加到私有列表?
- php - 在我的 LinkedIn Oauth2.0.php 访问令牌的获取功能中没有响应任何用户内容?
- php - 我想在视图中的循环中获取值的 id 并将其用于视图外的查询
- ruby - rails5:如何从搜索 api 中排除转发和回复?
- excel - 使用 Python 遍历 excel、站点地图
- android - 通过外部依赖排除支持的语言 (aar)
- python-3.x - str 对象没有属性批量注释图像