# coding=utf-8
import urllib.request
import urllib
import json
urllib2 = urllib.request
headers = {
# "Host":"fanyi.youdao.com",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0",
"Accept":"application/json, text/javascript, */*; q=0.01",
# "Accept-Language":"zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
# 以下这个不屏蔽会导致中文不能翻译成英文
# "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
"X-Requested-With":"XMLHttpRequest",
# "Content-Length":"209",
# "Connection":"keep-alive"
}
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&sessionFrom="
key = input("请输入要翻译的内容:")
formdata = {
"i":key,
"from":"AUTO",
"to":"AUTO",
"smartresult":"dict",
"client":"fanyideskweb",
"salt":"1525335936774",
"sign":"5747b87ca68723a7230af9cb648a04c1",
"doctype":"json",
"version":"2.1",
"keyfrom":"fanyi.web",
"action":"FY_BY_REALTIME",
"typoResult":"false"
}
# 转码
data = urllib.parse.urlencode(formdata).encode(encoding='UTF-8')
# print(data)
# 发送请求
request = urllib2.Request(url,data = data ,headers = headers)
response = urllib2.urlopen(request)
html = response.read().decode('utf-8')
# strip()去掉首位空格
print("完整的结果:",html.strip()+'\n')
# json文件读取
target = json.loads(html)
# 最终字典列表输出
# print(target["translateResult"][0][0]["tgt"])
if target["type"] == 'ZH_CN2EN':
print('"%s"的英文翻译结果为:%s'%(key,target["translateResult"][0][0]["tgt"]))
elif target["type"] == 'EN2ZH_CN'or 'JA2ZH_CN':
print('"%s"的中文翻译结果为:%s'%(key,target["translateResult"][0][0]["tgt"]))