import time
import requests
import random
import hashlib
import execjs
translate_url ='https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'
def get_translation_result(parameters):
headers={ 'User-Agent': user_agent,
'Host': 'fanyi.youdao.com',
'Origin': 'https://fanyi.youdao.com',
'Referer': 'https://fanyi.youdao.com/',
'X-Requested-With': 'XMLHttpRequest',
'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
'Cookie': 'OUTFOX_SEARCH_USER_ID="-1848382357@10.169.0.84"; ___rl__test__cookies=1625907853887; OUTFOX_SEARCH_USER_ID_NCOO=132978720.55854891'
}
response=requests.post(url=translate_url,headers=headers,data=parameters)
result=response.json()['translateResult'][0][0]['tgt']
return result
def get_parameters_by_python(query,translate_from,translate_to):
Its=str(int(time.time()*1000))
salt=Its+str(random.randint(0,9))
sign="fanyideskweb"+query+salt+"Ygy_4c=r#e#4EX^NUGUc5"
sign=hashlib.md5(sign.encode()).hexdigest()
bv=hashlib.md5(user_agent.encode()).hexdigest()
parameters={ 'i': query,
'from': translate_from,
'to': translate_to,
'smartresult': 'dict',
'client': 'fanyideskweb',
'salt': salt,
'sign': sign,
'Its': Its,
'bv': bv,
'doctype': 'json',
'version': '2.1',
'keyfrom': 'fanyi.web',
'action': 'FY_BY_REALTlME'
}
return parameters
def get_parameters_by_javascript(query,translate_from, translate_to):
with open('有道.js','r',encoding='utf-8') as f:
有道_js=f.read()
params = execjs.compile(有道_js).call('get_params', query, user_agent)
bv=hashlib.md5(user_agent.encode()).hexdigest()
parameters = {
'i': query,
'from': translate_from,
'to': translate_to,
'smartresult': 'dict',
'client': 'fanyideskweb',
'salt': params['salt'],
'sign': params['sign'],
'lts': params['lts'],
'bv': bv,
'doctype': 'json',
'version': '2.1',
'keyfrom': 'fanyi.web',
'action': 'FY_BY_REALTlME'
}
return parameters
def main():
query=input("输入翻译的名字:")
translate_from = translate_to = 'AUTO'
param= get_parameters_by_javascript(query, translate_from, translate_to)
result=get_translation_result(param)
print("翻译结果是",result)
if __name__=='__main__':
main()
未定义,怎么解决啊?,bug位置找到了,就是不知道咋解决