博文更新:
更新地址:https://blog.csdn.net/qq_40962368/article/details/89053068
原博文:
在调用有道翻译api接口时,出现了如下错误:
您要翻译的内容是:english
Traceback (most recent call last):File "D:/Python.workspace/Hello world/Web Spider/translate_test.py", line 34, in <module>translate_results = translate_results['translateResult'][0][0]['tgt']
KeyError: 'translateResult'
源代码如下:
from urllib import request
from urllib import parse
import json
i = input('您要翻译的内容是:')#对应上图的Request URLRequest_URL = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
#创建Form_Data字典,存储上图的Form DataForm_Data = {}Form_Data['from'] = 'AUTO'Form_Data['to'] = 'AUTO'Form_Data['i'] = iForm_Data['doctype'] = 'json'Form_Data['version'] = '2.1'Form_Data['keyfrom'] = 'fanyi.web'# Form_Data['ue'] = 'ue:UTF-8'Form_Data['action'] = 'FY_BY_REALTIME'
#使用urlencode方法转换标准格式data = parse.urlencode(Form_Data).encode('utf-8')#传递Request对象和转换完格式的数据response = request.urlopen(Request_URL, data)#读取信息并解码html = response.read().decode('utf-8')#使用JSONtranslate_results = json.loads(html)#找到翻译结果translate_results = translate_results['translateResult'][0][0]['tgt']#打印翻译信息print("翻译的结果是:%s" % translate_results)
百度了一下终于找到了问题所在,有道翻译的接口不是:
http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule
而是:http://fanyi.youdao.com/translate
Request_URL = 'http://fanyi.youdao.com/translate'
运行之后: