原因:
请求数据时,没有编码成UTF-8
对策:
data = urllib.parse.urlencode(url).encode(encoding=‘utf-8’)
urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None, quote_via=quote_plus)
Convert a mapping object or a sequence of two-element tuples, which may contain str or bytes objects, to a percent-encoded ASCII text string.
附上源代码
import urllib.request
import urllib.parse
import json
content=input('请输入需要翻译的内容:')
url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
data={}
data['i']=content
data['from']='AUTO'
data['to']='AUTO'
data['smartresult']='dict'
data['client']='fanyideskweb'
data['salt']='15887563211205'
data['sign']='4b838a13d4fe1cef23757c4fac68800e'
data['ts']='1588756321120'
data['bv']='8c141f1c08d20ba375b67e3d88fc7c4f'
data['doctype']='json'
data['version']='2.1'
data['keyfrom']='fanyi.web'
data['action']='FY_BY_REALTlME'
data=urllib.parse.urlencode(data).encode('utf-8')
#请求数据需要编码成utf-8,默认的是ASCII
response=urllib.request.urlopen(url,data)
html=response.read().decode('utf-8')
#python3.8默认编码形式是utf-8,因此可以写成html=response.read()
target=json.loads(html)
print('翻译结果是:%s'%(target['translateResult'][0][0]['tgt']))
本文介绍了解决在请求数据时未使用UTF-8编码导致的问题。通过将数据编码为UTF-8,确保了与服务器的正确通信。文章提供了Python代码示例,展示了如何使用urllib库进行正确的数据编码。


被折叠的 条评论
为什么被折叠?



