gpt4 book ai didi

python - 使用 urlopen.read 中的 "byte-like object"和 JSON?

转载 作者:IT老高 更新时间:2023-10-28 22:18:11 25 4
gpt4 key购买 nike

只是尝试测试非常简单的 Python JSON 命令,但遇到了一些麻烦。

urlopen('http://www.similarsitesearch.com/api/similar/ebay.com').read()

应该输出

'{"num":20,"status":"ok","r0":"http:\\/\\/www.propertyroom.com\\/","r1":"http:\\/\\/www.ubid.com\\/","r2":"http:\\/\\/www.bidcactus.com\\/","r3":"http:\\/\\/www.etsy.com\\/","r4":"http:\\/\\/us.ebid.net\\/","r5":"http:\\/\\/www.bidrivals.com\\/","r6":"http:\\/\\/www.ioffer.com\\/","r7":"http:\\/\\/www.shopgoodwill.com\\/","r8":"http:\\/\\/www.beezid.com\\/","r9":"http:\\/\\/www.webidz.com\\/","r10":"http:\\/\\/www.auctionzip.com\\/","r11":"http:\\/\\/www.overstock.com\\/","r12":"http:\\/\\/www.bidspotter.com\\/","r13":"http:\\/\\/www.paypal.com\\/","r14":"http:\\/\\/www.ha.com\\/","r15":"http:\\/\\/www.onlineauction.com\\/","r16":"http:\\/\\/bidz.com\\/","r17":"http:\\/\\/www.epier.com\\/","r18":"http:\\/\\/www.sell.com\\/","r19":"http:\\/\\/www.rasmus.com\\/"}'

但我得到了相同的字符串,前面有一个 b:

b'{"num":20,"status":"ok","r0":"http:\\/\\/www.propertyroom.com\\/","r1":"http:\\/\\/www.ubid.com\\/","r2":"http:\\/\\/www.bidcactus.com\\/","r3":"http:\\/\\/www.etsy.com\\/","r4":"http:\\/\\/us.ebid.net\\/","r5":"http:\\/\\/www.bidrivals.com\\/","r6":"http:\\/\\/www.ioffer.com\\/","r7":"http:\\/\\/www.shopgoodwill.com\\/","r8":"http:\\/\\/www.beezid.com\\/","r9":"http:\\/\\/www.webidz.com\\/","r10":"http:\\/\\/www.auctionzip.com\\/","r11":"http:\\/\\/www.overstock.com\\/","r12":"http:\\/\\/www.bidspotter.com\\/","r13":"http:\\/\\/www.paypal.com\\/","r14":"http:\\/\\/www.ha.com\\/","r15":"http:\\/\\/www.onlineauction.com\\/","r16":"http:\\/\\/bidz.com\\/","r17":"http:\\/\\/www.epier.com\\/","r18":"http:\\/\\/www.sell.com\\/","r19":"http:\\/\\/www.rasmus.com\\/"}'

随后,当我尝试运行时

json.loads(urlopen('http://similarsitesearch.com/api/similar/ebay.com').read())

它给了我错误信息:

TypeError: can't use a string pattern on a bytes-like object"

我假设这与 b 有关?

我从 urllib.request 导入了 urlopen,我正在运行 Python 3。

有什么想法吗?

最佳答案

read() 中的内容属于 bytes 类型,因此您需要先将其转换为字符串,然后再尝试将其解码为 json 对象。

要将 bytes 转换为字符串,请将代码更改为:urlopen('http://similarsitesearch.com/api/similar/ebay.com').read().decode("utf-8")

关于python - 使用 urlopen.read 中的 "byte-like object"和 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10846112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com