https://blog.csdn.net/yingshukun/article/details/53470424
https://my.oschina.net/auo/blog/222202
1 import urllib.request 2 import execjs 3 4 5 class Py4Js(): 6 7 def __init__(self): 8 self.ctx = execjs.compile(""" 9 function TL(a) { 10 var k = ""; 11 var b = 406644; 12 var b1 = 3293161072; 13 14 var jd = "."; 15 var $b = "+-a^+6"; 16 var Zb = "+-3^+b+-f"; 17 18 for (var e = [], f = 0, g = 0; g < a.length; g++) { 19 var m = a.charCodeAt(g); 20 128 > m ? e[f++] = m : (2048 > m ? e[f++] = m >> 6 | 192 : (55296 == (m & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (m = 65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023), 21 e[f++] = m >> 18 | 240, 22 e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224, 23 e[f++] = m >> 6 & 63 | 128), 24 e[f++] = m & 63 | 128) 25 } 26 a = b; 27 for (f = 0; f < e.length; f++) a += e[f], 28 a = RL(a, $b); 29 a = RL(a, Zb); 30 a ^= b1 || 0; 31 0 > a && (a = (a & 2147483647) + 2147483648); 32 a %= 1E6; 33 return a.toString() + jd + (a ^ b) 34 }; 35 36 function RL(a, b) { 37 var t = "a"; 38 var Yb = "+"; 39 for (var c = 0; c < b.length - 2; c += 3) { 40 var d = b.charAt(c + 2), 41 d = d >= t ? d.charCodeAt(0) - 87 : Number(d), 42 d = b.charAt(c + 1) == Yb ? a >>> d: a << d; 43 a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d 44 } 45 return a 46 } 47 """) 48 49 def getTk(self, text): 50 return self.ctx.call("TL", text) 51 52 53 54 def open_url(url): 55 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} 56 req = urllib.request.Request(url=url, headers=headers) 57 response = urllib.request.urlopen(req) 58 data = response.read().decode('utf-8') 59 return data 60 61 62 def translate(content, tk): 63 if len(content) > 4891: 64 print("翻译的长度超过限制!!!") 65 return 66 67 content = urllib.parse.quote(content) 68 69 url = "http://translate.google.cn/translate_a/single?client=t" 70 "&sl=en&tl=zh-CN&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca" 71 "&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&clearbtn=1&otf=1&pc=1" 72 "&srcrom=0&ssel=0&tsel=0&kc=2&tk=%s&q=%s" % (tk, content) 73 74 # 返回值是一个多层嵌套列表的字符串形式,解析起来还相当费劲,写了几个正则,发现也很不理想, 75 # 后来感觉,使用正则简直就是把简单的事情复杂化,这里直接切片就Ok了 76 result = open_url(url) 77 78 end = result.find("",") 79 if end > 4: 80 print(result[4:end]) 81 82 83 def main(): 84 js = Py4Js() 85 86 while 1: 87 content = input("输入待翻译内容:") 88 89 if content == 'q!': 90 break 91 92 tk = js.getTk(content) 93 translate(content, tk) 94 95 96 if __name__ == "__main__": 97 main()