UnicodeEncodeError:'latin-1'编解码器无法在位置8编码字符'\ u01e2':序数不在range256中怎么解决?

问题描述

我必须通过MobiDB提供的此代码访问db,以预测蛋白质中的疾病。

import urllib2
import json

# Define request
acceptHeader = 'My_File_TrEMBL.txt' # text/csv and text/plain supported
request = urllib2.Request("https://mobidb.org/ws/P04050/uniprot",headers={"Accept" : acceptHeader})

# Send request
response = urllib2.urlopen(request)

# Parse JSON response di Python dict
data = json.load(response)

# handle data
print(data)

由于我没有使用Python 2.6,因此更改了脚本,如下所示:

import urllib.request
import json

# Define request
acceptHeader ='My_File_TrEMBL.txt' 
# text/csv and text/plain supported
request = urllib.request.Request("https://mobidb.org/ws/P04050/uniprot",headers={"Accept" : 
acceptHeader})

# Send request
response = urllib.request.urlopen(request)

# Parse JSON response di Python dict
data = json.load(response)

# handle data
print(data)

所以我不使用urllib2而是urllib.request。当将变量请求传递到向我返回该实例的urllib.request.urlopen时,就会出现问题:

“'latin-1'编解码器无法在位置8编码字符'\ u01e2':序号不在范围(256)中”

我知道这与ASCII代码有关,但是由于我是Python的新手,所以我很想知道工作的截止日期,因此我希望您能提供任何帮助。 有义务

解决方法

使用utf-8编码对字节内容进行解码,并用json.loads读取内容

response = urllib.request.urlopen(request)
#get the content and decode it using utf-8
respcontent = response.read().decode('utf-8')
data = json.loads(respcontent)

print(data)