现在只是学到这么写,为什么这样写还得继续学习
方法一,在pipelines.py中自定义的自己的json类
class JsonWithEncodingPipeline(object):
def __init__(self):
self.file = codecs.open('article.json', 'w', encoding="utf-8")
def process_item(self, item, spider):
lines = json.dumps(dict(item), ensure_ascii=False) + "\n"#确保中文显示正常
self.file.write(lines)
return item
def spider_closed(self, spider):
self.file.close()
然后在settings.py中将其写入ITEM_PIPELINES函数中
'ArticleSpider.pipelines.JsonWithEncodingPipeline': 2
运行main.py,成功。
另一种是scrapy自带的将item转换成各种类型文件保存。
发现scrapy中可以将item转化成上述文件保存,例如Csv,Xml.
class JsonExporterPipeline(object):
#调用scrapy提供的json export 导出json文件
def __init__(self):
self.file = open('articleexport.json', 'wb')
self.exporter = JsonItemExporter(self.file, encoding = "utf-8", ensure_ascii=False)
self.exporter.start_exporting()
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
def close_spider(self,spider):
self.exporter.finish_exporting()
再到setting.py中修改ITEM_PIPELINES
'ArticleSpider.pipelines.JsonExporterPipeline': 2