- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我刚开始编程 Python。我想用scrapy创建一个bot,结果显示类型错误:当我运行项目时,“字节”类型的对象不是 JSON 可序列化的。
import json
import codecs
class W3SchoolPipeline(object):
def __init__(self):
self.file = codecs.open('w3school_data_utf8.json', 'wb', encoding='utf-8')
def process_item(self, item, spider):
line = json.dumps(dict(item)) + '\n'
# print line
self.file.write(line.decode("unicode_escape"))
return item
from scrapy.spiders import Spider
from scrapy.selector import Selector
from w3school.items import W3schoolItem
class W3schoolSpider(Spider):
name = "w3school"
allowed_domains = ["w3school.com.cn"]
start_urls = [
"http://www.w3school.com.cn/xml/xml_syntax.asp"
]
def parse(self, response):
sel = Selector(response)
sites = sel.xpath('//div[@id="navsecond"]/div[@id="course"]/ul[1]/li')
items = []
for site in sites:
item = W3schoolItem()
title = site.xpath('a/text()').extract()
link = site.xpath('a/@href').extract()
desc = site.xpath('a/@title').extract()
item['title'] = [t.encode('utf-8') for t in title]
item['link'] = [l.encode('utf-8') for l in link]
item['desc'] = [d.encode('utf-8') for d in desc]
items.append(item)
return items
追溯:
TypeError: Object of type 'bytes' is not JSON serializable
2017-06-23 01:41:15 [scrapy.core.scraper] ERROR: Error processing {'desc': [b'\x
e4\xbd\xbf\xe7\x94\xa8 XSLT \xe6\x98\xbe\xe7\xa4\xba XML'],
'link': [b'/xml/xml_xsl.asp'],
'title': [b'XML XSLT']}
Traceback (most recent call last):
File
"c:\users\administrator\appdata\local\programs\python\python36\lib\site-p
ackages\twisted\internet\defer.py", line 653, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "D:\LZZZZB\w3school\w3school\pipelines.py", line 19, in process_item
line = json.dumps(dict(item)) + '\n'
File
"c:\users\administrator\appdata\local\programs\python\python36\lib\json\_
_init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File
"c:\users\administrator\appdata\local\programs\python\python36\lib\json\e
ncoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File
"c:\users\administrator\appdata\local\programs\python\python36\lib\json\e
ncoder.py", line 257, in iterencode
return _iterencode(o, 0)
File
"c:\users\administrator\appdata\local\programs\python\python36\lib\
json\encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'bytes' is not JSON serializable
最佳答案
您正在自己创建那些 bytes
对象:
item['title'] = [t.encode('utf-8') for t in title]
item['link'] = [l.encode('utf-8') for l in link]
item['desc'] = [d.encode('utf-8') for d in desc]
items.append(item)
每个 t.encode()
、l.encode()
和 d.encode()
调用都会创建一个 字节
字符串。不要这样做,将其留给 JSON 格式以序列化这些。
接下来,您还犯了其他几个错误;你在没有必要的地方编码太多。将其留给 json
模块和 open()
调用返回的 standard 文件对象来处理编码。
您也不需要将您的 items
列表转换为字典;它已经是一个可以直接进行 JSON 编码的对象:
class W3SchoolPipeline(object):
def __init__(self):
self.file = open('w3school_data_utf8.json', 'w', encoding='utf-8')
def process_item(self, item, spider):
line = json.dumps(item) + '\n'
self.file.write(line)
return item
我猜您学习的教程假定使用 Python 2,但您使用的是 Python 3。我强烈建议你找一个不同的教程;它不仅是为过时版本的 Python 编写的,如果它提倡 line.decode('unicode_escape')
,它还会教给一些极坏的习惯,这些习惯会导致难以跟踪的错误。我可以推荐你看看 Think Python, 2nd edition获取一本关于学习 Python 3 的免费好书。
关于python - 类型错误 : Object of type 'bytes' is not JSON serializable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44682018/
实现了Serializable接口(interface)的类的子类是否也实现了Serializable?也就是说子类的实例也可以序列化吗? 最佳答案 I wanted to ask whether t
当对象可序列化或不可序列化时,将数据对象保存到数据库有什么不同。 例如:我有一个名为 Book 的域类 class Book implements Serializable{ private int
我的理解是conflict serializable 隐含serializable。我不确定这如何让他们与众不同。可序列化是否意味着冲突可序列化? 最佳答案 冲突可序列化是可序列化的一个子集,因此仅仅
我正在阅读接口(interface) Serializable 的文档,我在其中找到以下几行: To allow subtypes of non-serializable classes to be
scala @Serializable 的 Action 方式与Java Serializable 不同吗? 我的意思是序列化对象的方式还是两者都使用相同的标准序列化? 最佳答案 Scala 可以编译
我遇到过使用这两种表示法中的任何一种的例子。我找不到关于它的任何信息,说明哪一个是常见的,为什么允许使用 2 个符号,以及两者之间是否存在任何细微差别。 有人有想法吗? 最佳答案 不,没有功能差异。
“可序列化”类中的字段应该是 transient 的或可序列化的,可以修复在另一个类中使用的任何实体/类,但当在甚至无法创建的 dto 类中声明 List/Map 时,就会发生这种情况也一样短暂。请让
我面临任务不可序列化的问题,我检查了其他答案并使我的调用和调用类可序列化。我的代码就像 - public class MultiClassification implements Serializab
我到处都读到 Java Serializable 比 Parcelable 慢得多。 Kotlin Serializable 也是这样吗?或者 Kotlin Serializable 和 Kotlin
描述: 我有一个 ArrayList,它接受任何实现 Serializable 的类。我什至可以将实现 Serializable 的类的实例添加到这个数组列表中,而不会出现任何编译错误。 Java 泛
我正在实现一个可序列化的类(因此它是一个使用 RMI 的值对象)。但我需要测试它。有没有办法轻松做到这一点? 澄清:我正在实现这个类,所以在类定义中粘贴 Serializable 很简单。我需要手动对
我尝试执行以下简单代码。 System.out.println() 不打印单词“Serialized:”。输出为true。 ArrayList arrayList = new ArrayList();
伙计们,我有一个最简单的类,我想成为 Parcelable。我正在按照以下方式进行: public class MyField implements Serializable, Parcelable
我的问题与this 非常相似除了这个问题我在 SonarLint V3 (squid:S1948) 中遇到过。 我的代码是: public class Page implements Serializ
考虑下面的类(class)。如果我对它运行 Findbugs,它会在第 5 行但不在第 7 行给我一个错误(“可序列化类中的非 transient 非可序列化实例字段”)。 1 public clas
当我在 Spark(由 java 编写)应用程序中使用 UDF 函数时,出现此错误。 org.apache.spark.SparkException:任务不可序列化 在 org.apache.spar
我正在使用KTOR框架在我的Android应用程序中发出http请求。我在运行项目时遇到错误。。插件:。依赖关系:。模型类:。接口调用:。我花了几个小时寻找解决方案。我遵循了许多线索,但都没有奏效。我
我发现有人回答了可线性化和可串行化之间的差异,但我没有发现有人说可串行化与顺序一致性相同或不同。 此外,我在不同的文章、书籍和网页中对上述术语的不同定义感到震惊,我把这一切都搞糊涂了。 有人可以解释可
我读过几个相关的问题,但没有一个是更有趣的情况。 这是我的问题,假设我有课 class A implements Serializable { private int a; priva
我注意到在 Spring-boot 中很多人创建模型/实体并实现 Serialiazable 接口(interface)。 public class ModelBase implements Seri
我是一名优秀的程序员,十分优秀!