def youdao():
import json
import execjs
import hashlib
import requests
word=input('请输入需要翻译的汉语:')
jscode = """
function foo(e) {
r = "" + (new Date).getTime()
i = r + parseInt(10 * Math.random(), 10);
return {
ts: r,
salt: i,
}
};
"""
js_evn = execjs.compile(jscode)
res = js_evn.call("foo", word)
md5 = hashlib.md5()
# 加盐 + 翻译单词 + 14位时间戳 + 加盐
s = "fanyideskweb" + word + res["salt"] + "Tbh5E8=q6U3EXe+&L[4c@"
md5.update(s.encode())
sign = md5.hexdigest()
# print(res["ts"], res["salt"], sign)
data = {
"i": word,
"from": "AUTO",
"to": "AUTO",
"smartresult": "dict",
"client": "fanyideskweb",
"salt": res["salt"],
"sign": sign,
"lts": res["ts"],
"bv": "4f7ca50d9eda878f3f40fb696cce4d6d",
"doctype": "json",
"version": "2.1",
"keyfrom": "fanyi.web",
"action": "FY_BY_CLICKBUTTION",
}
# 请求头
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9",
"Connection": "keep-alive",
"Content-Length": "243",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Cookie": 'OUTFOX_SEARCH_USER_ID_NCOO=1536667068.8073757; OUTFOX_SEARCH_USER_ID="-618076274@10.108.160.17"; JSESSIONID=aaac-gu43n3IPcb5uQbDx; ___rl__test__cookies=1611714444863',
"Host": "fanyi.youdao.com",
"Origin": "http://fanyi.youdao.com",
"Referer": "http://fanyi.youdao.com/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
}
# 请求地址
url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
response = requests.post(url, data=data, headers=headers)
html = response.content.decode()
html = json.loads(html)
for item in html['translateResult'][0]:
results = item['tgt']
print(results)
if __name__ == '__main__':
youdao()