import json
import time
import random
import hashlib
import requests
def youdao_fanyi(key):
baseurl = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
# 计算时间戳13位
time_span = int(time.time()*1000)
lts = str(time_span)
# salt 为lts后添加一位随机数,凑成14位
salt = str(time_span*10 + random.randint(0, 10))
# sign 计算方式
s = "fanyideskweb" + key + salt + "]BjuETDhU)zqSxf-=B#7m"
sign = hashlib.md5(s.encode()).hexdigest()
# navigator.appVersion,固定,可以使用固定值
agent = "5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36"
bv = hashlib.md5(agent.encode()).hexdigest()
data = {
"i" : key,
"from" : "AUTO",
"to" : "AUTO",
"smartresult" : "dict",
"client" : "fanyideskweb",
"salt" : salt,
"sign" : sign,
"lts" : lts,
"bv" : bv,
"doctype" : "json",
"version" : "2.1",
"keyfrom" : "fanyi.web",
"action" : "FY_BY_REALTlME"
}
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding" : "gzip, deflate",
"Accept-Language" : "zh-CN,zh;q=0.9,en-GB;q=0.8,en;q=0.7",
"Connection" : "keep-alive",
"Content-Length" : str(len(key)),
"Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8",
"Cookie" : "OUTFOX_SEARCH_USER_ID=1195241757@10.108.160.101; JSESSIONID=aaaewgbb34F9kdlA9wswx; OUTFOX_SEARCH_USER_ID_NCOO=1539706065.7723656; ___rl__test__cookies=1604559693998",
"Host" : "fanyi.youdao.com",
"Origin" : "http://fanyi.youdao.com",
"Referer" : "http://fanyi.youdao.com/",
"User-Agent" : "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36",
"X-Requested-With" : "XMLHttpRequest"
}
response =requests.post(url=baseurl, data=data, headers = headers)
# json大概内容
"""
{
"translateResult": [
[{
"tgt": "Please use",
"src": "请使用"
}]
],
"errorCode": 0,
"type": "zh-CHS2en"
}
"""
if response.status_code == 200:
# print(response.text)
result = response.json()
else:
result = {}
if result.get("errorCode")==0:
str_result = "翻译结果:"
data_list = result.get('translateResult')[0]
for item in data_list:
str_result += item.get('tgt')
return str_result
else:
return key
if __name__ == "__main__":
key = input("翻译的内容:")
print(youdao_fanyi(key))
|