本篇为实现谷歌翻译的功能,在编写的时候以为只是一个接口的问题。

没想到的是每次翻译都会触发一次JS的执行,在请求参数中生成一个tk。

文中tk的实现是复用的网上大神的代码生成tk。

好了,不说了直接看代码吧!

 # /usr/bin/env python
# -*- coding: utf- -*-
import urllib.parse
import execjs,requests,termcolor class Return_tk(): def __init__(self):
self.ctx = execjs.compile("""
function TL(a) {
var k = "";
var b = ;
var b1 = ; var jd = ".";
var $b = "+-a^+6";
var Zb = "+-3^+b+-f"; for (var e = [], f = , g = ; g < a.length; g++) {
var m = a.charCodeAt(g);
> m ? e[f++] = m : ( > m ? e[f++] = m >> | : ( == (m & ) && g + < a.length && == (a.charCodeAt(g + ) & ) ? (m = + ((m & ) << ) + (a.charCodeAt(++g) & ),
e[f++] = m >> | ,
e[f++] = m >> & | ) : e[f++] = m >> | ,
e[f++] = m >> & | ),
e[f++] = m & | )
}
a = b;
for (f = ; f < e.length; f++) a += e[f],
a = RL(a, $b);
a = RL(a, Zb);
a ^= b1 || ;
> a && (a = (a & ) + );
a %= 1E6;
return a.toString() + jd + (a ^ b)
}; function RL(a, b) {
var t = "a";
var Yb = "+";
for (var c = ; c < b.length - ; c += ) {
var d = b.charAt(c + ),
d = d >= t ? d.charCodeAt() - : Number(d),
d = b.charAt(c + ) == Yb ? a >>> d: a << d;
a = b.charAt(c) == Yb ? a + d & : a ^ d
}
return a
}
""") def getTk(self, text):
return self.ctx.call("TL", text) def open_url(url):
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'}
req = requests.get(url=url, headers=headers)
return req.content.decode('utf-8') def max_length(content):
if len(content) > :
print("翻译文本超过限制!")
return def print_result(parm):
result = parm
str_end = result.find("\",")
if str_end > :
print("翻译的结果为:",result[:str_end]) def en_to_zn_translate(content, tk):
max_length(content)
content = urllib.parse.quote(content)
#英译汉
url = "http://translate.google.cn/translate_a/single?client=t" \
"&sl=en&tl=zh-CN&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca" \
"&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&clearbtn=1&otf=1&pc=1" \
"&srcrom=0&ssel=0&tsel=0&kc=2&tk=%s&q=%s" % (tk, content)
result = open_url(url)
print_result(result) def zn_to_en_translate(content,tk):
max_length(content)
content = urllib.parse.quote(content)
#汉译英
url = "http://translate.google.cn/translate_a/single?client=t"\
"&sl=zh-CN&tl=en&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca"\
"&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8"\
"&source=btn&ssel=3&tsel=3&kc=0&tk=%s&q=%s"%(tk,content)
result = open_url(url)
print_result(result) def main():
js = Return_tk()
while True:
print(termcolor.colored("请先输入要进行的操作:q表示退出;e表示英文翻译成中文;z表示中文翻译成英文。","red"))
change = input("请选择翻译选项:")
if change == 'q':
break
elif change == 'e':
content = input("请输入要翻译的英文:")
tk = js.getTk(content)
en_to_zn_translate(content,tk)
elif change == 'z':
content = input("请输入要翻译的中文:")
tk = js.getTk(content)
zn_to_en_translate(content,tk)
else:
print("请输入正确的选项!") main()

见运行效果:

Python3 动手自己写谷歌翻译-LMLPHP

总结:

从代码上来看,写的比较简洁,没有高大上的写法,只是单纯的实现一个功能。

除了tk的生成封装成了类,其他的全部是用函数式编程实现。

05-26 18:50