我从互联网(Stackoverflow API)获取JSON并尝试解码它:
import urllib.request
url = "https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow"
fp = urllib.request.urlopen(url)
mybytes = fp.read()
mystr = mybytes.decode("utf8")
fp.close()
print(mystr)
我收到了错误:
Traceback(最近一次调用最后一次):文件“code.py”,第6行,in mystr = mybytes.decode(“utf8”)UnicodeDecodeError:'utf-8'编解码器无法解码位置1的字节0x8b:无效的起始字节
为什么以及如何解决?
答案 0 :(得分:2)
使用requests:
import requests
url = "https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow"
res = requests.get(url)
if res.status_code == 200:
print(res.json())
答案 1 :(得分:0)
编码和解码utf-8在python中似乎很棘手。我建议也包括.encode()。
import urllib.request
url = "https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow"
fp = urllib.request.urlopen(url)
mybytes = fp.read()
mystr = mybytes.encode().decode()
fp.close()
print(mystr)
此外,是的,请使用请求。太棒了:http://docs.python-requests.org/en/master/