从百度翻译中获取到的发送和处理翻译请求的js代码
// baidu.js文件
// 生成sign代码
var i = null; // e 函数中需要使用的参数,通过源代码中查得
function n(r, o) { // 通过打断点单步调试可以知道r参数为要翻译的内容
for (var t = 0; t < o.length - 2; t += 3) {
var a = o.charAt(t + 2);
a = a >= "a" ? a.charCodeAt(0) - 87 : Number(a),
a = "+" === o.charAt(t + 1) ? r >>> a : r << a,
r = "+" === o.charAt(t) ? r + a & 4294967295 : r ^ a
}
return r
}
function e(r,gtk) { // 通过打断点单步调试可以知道 r 参数为要翻译的内容,通过源js代码中对sign数据处打断点,找到生成函数为 e 函数
var o = r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g);
if (null === o) {
var t = r.length;
t > 30 && (r = "" + r.substr(0, 10) + r.substr(Math.floor(t / 2) - 5, 10) + r.substr(-10, 10))
} else {
for (var e = r.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/), C = 0, h = e.length, f = []; h > C; C++)
"" !== e[C] && f.push.apply(f, a(e[C].split(""))),
C !== h - 1 && f.push(o[C]);
var g = f.length;
g > 30 && (r = f.slice(0, 10).join("") + f.slice(Math.floor(g / 2) - 5, Math.floor(g / 2) + 5).join("") + f.slice(-10).join(""))
}
var u = void 0
, l = "" + String.fromCharCode(103) + String.fromCharCode(116) + String.fromCharCode(107);
u = null !== i ? i : (i = gtk || "") || ""; // 单步调试后源js代码中的window[l]值为gtk,这个值可以从请求返回的html中获取,将其直接换成gtk之后,使用request获取后作为参数传入即可
for (var d = u.split("."), m = Number(d[0]) || 0, s = Number(d[1]) || 0, S = [], c = 0, v = 0; v < r.length; v++) {
var A = r.charCodeAt(v);
128 > A ? S[c++] = A : (2048 > A ? S[c++] = A >> 6 | 192 : (55296 === (64512 & A) && v + 1 < r.length && 56320 === (64512 & r.charCodeAt(v + 1)) ? (A = 65536 + ((1023 & A) << 10) + (1023 & r.charCodeAt(++v)),
S[c++] = A >> 18 | 240,
S[c++] = A >> 12 & 63 | 128) : S[c++] = A >> 12 | 224,
S[c++] = A >> 6 & 63 | 128),
S[c++] = 63 & A | 128)
}
for (var p = m, F = "" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(97) + ("" + String.fromCharCode(94) + String.fromCharCode(43) + String.fromCharCode(54)), D = "" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(51) + ("" + String.fromCharCode(94) + String.fromCharCode(43) + String.fromCharCode(98)) + ("" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(102)), b = 0; b < S.length; b++)
p += S[b],
p = n(p, F);
return p = n(p, D),
p ^= s,
0 > p && (p = (2147483647 & p) + 2147483648),
p %= 1e6,
p.toString() + "." + (p ^ m)
}
python代码运行JS
import execjs
import requests
import re
import json
headers = {
"Accept":"*/*",
"X-Requested-With":"XMLHttpRequest",
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36",
"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
"Origin":"https://fanyi.baidu.com",
"Sec-Fetch-Site":"same-origin",
"Sec-Fetch-Mode":"cors",
"Sec-Fetch-Dest":"empty",
"Referer":"https://fanyi.baidu.com/"
}
session = requests.Session() # 创建session对象
session.headers = headers
def get_data():
'''
:获取gtk和token的值
'''
URL = 'https://fanyi.baidu.com/'
session.get(URL) # 请求一次拿不到token数据,所以需要请求第二次
req = session.get(URL)
token = re.findall(r"token: '(.*?)',", req.text)[0]
gtk = re.findall(r";window.gtk = '(.*)';",req.text)[0]
data_dict = {'token':token,'gtk':gtk}
return data_dict
def get_sign(query):
'''
:获取sign值
'''
# 读取JS代码文件
datas = get_data() # 从get_data方法中获取gtk和token的值
gtk = datas['gtk']
token = datas['token']
with open('./baidu.js','r',encoding='utf-8') as f:
baidu_js = f.read()
# 编译读取到的js代码为python可执行的代码
py_js = execjs.compile(baidu_js)
# 运行js代码,获取sign值
sign = py_js.call('e',query,gtk)
data_list = [token,sign]
return data_list
def get_translation(query):
datas = get_sign(query) # 使用get_sign方法获取token和sign的值
token = datas[0]
sign = datas[1]
req_url = 'https://fanyi.baidu.com/v2transapi?from=zh&to=en'
form_data = {
"from": "zh",
"to": "en",
"query": query,
"transtype": "realtime",
"simple_means_flag": "3",
"sign": sign,
"token": token,
"domain": "common"
}
req = session.post(req_url,data=form_data)
trans_content = re.findall('"dst":"(.*?)"', req.text)[0]
# print(json.loads(req.text)['trans_result']['data'][0]['dst']) # 当传入的表单数据选择不同的语种翻译时,使用json取翻译的数据
print('%s:%s'%(query,trans_content))
if __name__ == '__main__':
query = input('输入需要翻译的内容:')
translation = get_translation(query)
代码尚有改进的地方:可以获取html中的所有语言种类,在运行的时候选择对应的语言进行翻译(调用get_translation方法的时候将要翻译和翻译后的语种作为参数传入form表单中实现多种语言的翻译)