源代码
import json
from urllib.request import Request, urlopen
from urllib.parse import urlencode
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
url = ' ' # 请求的API接口
headers = {
'User-Agent': ' ',
'Cookie': ' ',
'x-requested-with': 'XMLHttpRequest'
}
def fanyi(kw):
data = {
'kw': kw
}
# Request() 中的data参数是byte类型
# data不为空时,是post请求
req = Request(url,
data=urlencode(data).encode('utf-8'),
headers=headers)
resp = urlopen(req)
assert resp.code == 200
json_data = resp.read() # byte
content_encode = resp.getheader('Content-Type')
content_encode = 'utf-8' if content_encode is None else content_encode.split('=')[-1]
return json.loads(json_data.decode(content_encode))
if __name__ == '__main__':
print(fanyi('orange'))
解决以上代码报错:return json.loads(json_data.decode(content_encode))
LookupError: unknown encoding: application/json
要解决return json.loads(json_data.decode(content_encode))代码行中的LookupError: unknown encoding: application/json错误,可以使用try-except语句来捕捉该异常,并使用默认的UTF-8编码处理 JSON 数据。
更新的代码如下所示:
try:
return json.loads(json_data.decode(content_encode))
except LookupError:
return json.loads(json_data.decode('utf-8'))
在这个更新的代码中,我们尝试使用 content_encode 解码 JSON 数据。如果发生 LookupError 异常,说明编码未知或无法识别为有效的编码格式。在这种情况下,我们将使用默认的 utf-8 编码来解码 JSON 数据。
这样,即使出现编码未知的情况,代码也能正确处理并解码 JSON 数据。
更新后的代码应该能够正确处理 JSON 数据,并解决LookupError: unknown encoding: application/json错误。