1. 对字典中的键赋值应该使用引号不是冒号
2. 这样做有可能被反爬,帮你加了个 headers
3. 是 translateResult 不是 translateresult
代码帮你改好了:
import urllib.request as r
import urllib.parse as p
import json
content = input('输入需要翻译的内容:')
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
data = {}
data['i'] = content
data['from'] = 'en'
data['to'] = 'zh-CHS'
data['smartresult'] = 'dict'
data['client'] = 'fanyideskweb'
data['salt'] = '15973481492248'
data['sign'] = '17fd1500de801cd7d934942cff5e19f8'
data['lts'] = '1597348149224'
data['bv'] = '3b8d467d426f612bd369aee663a42d43'
data['doctype'] = 'json'
data['version'] = '2.1'
data['keyfrom'] = 'fanyi.web'
data['action'] = 'FY_BY_REALTlME'
data1 = p.urlencode(data).encode()
headers = {'User-Agent': 'Mozilla/5.0'}
response = r.urlopen(r.Request(url, headers=headers),data1)
html = response.read().decode('utf-8')
target = json.loads(html)
print('翻译结果:%s' % target['translateResult'][0][0]['tgt'])
|