环境:windows7,python3.5,Spyder,火狐浏览器
首先,本文章是参考大神资料中遇到一些问题,在此做一个记录。大神博客链接:点击打开链接
先贴问题:
(1)KeyError: 'translateResult'
from urllib import request
from urllib import parse
import json
Request_URL = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
#创建Form_Data字典,存储上图的Form Data
Form_Data = {}
Form_Data['type'] = 'AUTO'
Form_Data['i'] = 'Jack'
Form_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')
#使用JSON
translate_results = json.loads(html)
#找到翻译结果
translate_results = translate_results['translateResult'][0][0]['tgt']
#打印翻译信息
print("翻译的结果是:%s" % translate_results)
修改位置:将Request_URL中 translate_o 改为 translate(亲测有效,网上也都这么搞,没搞明白为啥)
(2)HTTPError: Internal Server Error
这个问题应该是因浏览器而异,参考的博客中是:Form_Data['xmlVersion'] = '1.8'
在火狐浏览器中需要修改为:
Form_Data['Version'] = '2.1'
参下(火狐->有道->查看元素->网络->参数):Form_Data['action'] = 'FY_BY_REALTIME'
action FY_BY_REALTIME
client fanyideskweb
doctype json
from AUTO
i Jack
keyfrom fanyi.web
salt 1527300503556
sign 5cb0bbc51b1b96a51f74796335e854ae
smartresult dict
to AUTO
typoResult false
version 2.1