修改前代码:
import urllib.request
import urllib.parse
import json
content = input("请输入需要翻译的内容: ")
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
head = {}
head['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
data = {}
data['i'] = content
data['from'] = 'AUTO'
data['to'] = 'AUTO'
data['smartresult'] = 'dict'
data['client'] = 'fanyideskweb'
data['doctype'] = 'json'
data['version'] = '2.1'
data['keyfrom'] = 'fanyi.web'
data['action'] = 'FY_BY_REALTIME'
data['typoResult'] = 'false'
data = urllib.parse.urlencode(data).encode('utf-8')
response = urllib.request.urlopen(url,data)
html = response.read().decode('utf-8')
target = json.loads(html)
print("翻译结果: %s" %(target['translateResult'][0][0]['tgt']))
运行后出现:
{"errorCode":50}
参考:点击打开链接
去掉url中的_o即可进行翻译
得到结果:
请输入需要翻译的内容: hello
翻译结果: 你好