scrapy_TypeError: Object of type 'QiubaiItem' is not JSON serializable

问题描述:

使用scrapy对糗事百科进行爬虫的时,在spider文件中返回在items文件的实例化对象,然后在管道文件进行磁盘持久化的时候,想将从spider文件传过来的数据通过json转换成字符串然后在写入文件,结果报错

Traceback (most recent call last):
  File "e:\anaconda3\lib\site-packages\twisted\internet\defer.py", line 654, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File "E:\Scrapy\Qiubai\Qiubai\pipelines.py", line 19, in process_item
    self.f.write(json.dumps(item, ensure_ascii=False) + ",\n")
  File "e:\anaconda3\lib\json\__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "e:\anaconda3\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "e:\anaconda3\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "e:\anaconda3\lib\json\encoder.py", line 180, in default
    o.__class__.__name__)

代码如下:

class QiubaiPipeline(object):
    def open_spider(self, spider):
        self.f = open("糗百.json", "a", encoding="utf-8")

    def process_item(self, item, spider):
        self.f.write(json.dumps(item, ensure_ascii=False) + ",\n")
        print("保存成功")

        return item

    def close_spider(self, spider):
        self.f.close()

原因分析:

既然不能使用json进行转换,那么就打印它的数据类型

import json


class QiubaiPipeline(object):
    def open_spider(self, spider):
        self.f = open("糗百.json", "a", encoding="utf-8")

    def process_item(self, item, spider):
        print("process_item")
        print(type(item))
        self.f.write(json.dumps(item, ensure_ascii=False) + ",\n")
        print("保存成功")

        return item

    def close_spider(self, spider):
        self.f.close()
process_item
<class 'Qiubai.items.QiubaiItem'>

百度了下:

解决方式是自己定义一个类,当遇到报错类型的数据时,就直接转换成字符串。

我这里给出的解决方案:

先将从spider文件传过来的数据使用dict()进行数据类型的转换成字典,然后在使用如下代码进行磁盘持久化。

self.f.write(json.dumps(dict(item), ensure_ascii=False) + ",\n")

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值