# V1.0
"""
文件 YDtranslate.py
时间 2021/02/23 20:26:37
"""
import requests
import time
import random
import hashlib
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
i = input("输入单词:")
lts = str(int(round(time.time() * 1000))) # 十三位时间戳
salt = lts + str(random.randint(0, 9)) # 十三位时间戳加一位随机数
s = "fanyideskweb" + i + salt + "Tbh5E8=q6U3EXe+&L[4c@"
sign = hashlib.md5(s.encode("utf-8")).hexdigest()
bv = hashlib.md5(
"5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36".encode(
"utf-8"
)
).hexdigest()
headers = {
"Referer": "http://fanyi.youdao.com/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36",
"Connection": "keep-alive",
"Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/x-www-form-urlencoded;", # ! charset=UTF-8 导致无法将中文翻译成英文
"Origin": "http://fanyi.youdao.com",
"Accept-Language": "zh-CN,zh;q=0.9",
"Cookie": "OUTFOX_SEARCH_USER_ID=-368708839@10.108.160.18; JSESSIONID=aaaL2DMAbpTgg8Qpc2xUw; OUTFOX_SEARCH_USER_ID_NCOO=1451460344.418452; ___rl__test__cookies=1561684330987",
}
data = {
"i": i,
"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",
}
response = requests.post(url=url, headers=headers, data=data).json()
result = response["translateResult"][0][0]["tgt"]
print(result)
|