我们知道百度翻译API套餐8月份调整了,但是网页上我们是可以进行免费翻译的,使用F12抓包可以得到一个百度翻译的接口,但是在提交数据时,需要提交一个sign值才能成功获得翻译结果,而这个sign值跟需要翻译的字符串相关,下面为python实现步骤?
创建js文件
代码如下:
var i = "320305.131321201"; function n(r, o) { 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) { 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 = window[l] || "") || ""; 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) }
这个代码怎么来的,网上有很多教程,但是断点调试这块我是看不懂,有兴趣的自己可以找文章研究
实现代码
import os import requests import execjs os.environ["EXECJS_RUNTIME"] = "Node" str = "今天天气真不错" with open("./text/baidufanyi.js", "r") as fp: js_data = fp.read() sign = execjs.compile(js_data).call("e", str) print(sign)
说明
- baidufanyi.js即为上面创建的js文件
- 字符串长度大于30的时候,execjs解析的结果和浏览器解析的结果会有差异,所以需要安装nodejs进行解析
- 如果是使用pycharm,配置nodejs后需要重启pycharm。
- 百度翻译中其他参数,headers参数User-Agent、Cookie、和数据中的token均可以直接从抓包中获取,token是固定的
转载请注明:思享SEO博客 » python获取百度翻译接口sign值