python爬数据保存json_Python爬虫学习12-爬取数据保存为json

在Python Scrapy框架中,通过设置自定义pipelines可以将爬取的数据保存为JSON文件。有两种方法实现:1) 使用Scrapy内置的JsonItemExporter;2) 自定义方法,利用codecs和json库进行数据转换和写入。确保使用ensure_ascii=False来正确处理非英文字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Scrapy中,所有item数据都会通过pipelines进行处理,想要保存为json格式文件,只需要在piplines中进行相应的处理即可。

1、使用系统模块导出json

from scrapy.exporters import JsonItemExporter

class JsonExporterPipeline(object):

def __init__(self):

self.file = open('articlejson.json', 'wb')

self.exporter = JsonItemExporter(self.file, encoding="utf-8", ensure_ascii=False)

self.exporter.start_exporting()

def close_spider(self, spider):

self.exporter.finish_exporting()

self.file.close()

def process_item(self, item, spider):

self.exporter.export_item(item)

return item

2、自定义

在pipelines.py中加入以下代码

import codecs

import 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()

说明:

codecs 避免打开文件时出现编码错误。

json.dumps : dict转成str

json.loads: str转成dict

ensure_ascii=False: 避免处理英文以外语言时出错

return item:交给下一个pipeline处理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值