如果要對網頁正文進行翻譯,可直接參考:https://blog.csdn.net/qq_42632840/article/details/101938081
谷歌翻譯介紹
谷歌翻譯網址:https://translate.google.cn/
Google 翻譯是谷歌公司提供一項免費的翻譯服務,可提供103 種語言之間的即時翻譯,支持任意兩種語言之間的字詞、句子和網頁翻譯。
實現谷歌翻譯的方法
經過查找資料,python實現谷歌翻譯大概有三類方法:
1.使用google API
此方法需要付費,然後綁定項目和google賬號,啓動API,創建service account,具體可見:https://blog.csdn.net/nicolelili1/article/details/76973097
2.使用別人已經封裝好的一些庫
3.通過爬蟲實現翻譯,本文主要實現這方法
通過爬蟲實現谷歌翻譯
首先給出代碼:
Py4Js.py:
import execjs
class Py4Js():
def __init__(self):
self.ctx = execjs.compile("""
function TL(a) {
var k = "";
var b = 406644;
var b1 = 3293161072;
var jd = ".";
var $b = "+-a^+6";
var Zb = "+-3^+b+-f";
for (var e = [], f = 0, g = 0; g < a.length; g++) {
var m = a.charCodeAt(g);
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),
e[f++] = m >> 18 | 240,
e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224,
e[f++] = m >> 6 & 63 | 128),
e[f++] = m & 63 | 128)
}
a = b;
for (f = 0; f < e.length; f++) a += e[f],
a = RL(a, $b);
a = RL(a, Zb);
a ^= b1 || 0;
0 > a && (a = (a & 2147483647) + 2147483648);
a %= 1E6;
return a.toString() + jd + (a ^ b)
};
function RL(a, b) {
var t = "a";
var Yb = "+";
for (var c = 0; c < b.length - 2; c += 3) {
var d = b.charAt(c + 2),
d = d >= t ? d.charCodeAt(0) - 87 : Number(d),
d = b.charAt(c + 1) == Yb ? a >>> d: a << d;
a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d
}
return a
}
""")
def getTk(self, text):
return self.ctx.call("TL", text)
google_trans.py:
from Py4Js import *
import requests
# 谷歌翻譯方法
def google_translate(content):
'''實現谷歌的翻譯'''
res_trans=""
# print(js)
if len(content)>4891:
while len(content) > 4891:
#print("翻譯的長度超過限制!!!")
# temp=content[0:4000-len(content[0:4000].split('.')[-1])]+content[4000].split('.')[0]
# content=content[4001-len(content[0:4000].split('.')[-1]):]
temp=content[0:4889]
content=content[4890:]
print(content+"\n\n")
temp_trans=google_trans_final(temp)
res_trans=res_trans+temp_trans
#google_translate(content)
print("實現多次翻譯拼接,用這個分割一下\n\n")
#return
temp_trans=google_trans_final(content)
res_trans+=temp_trans
return res_trans
else:
return google_trans_final(content)
def google_trans_final(content):
js = Py4Js()
tk = js.getTk(content)
param = {'tk': tk, 'q': content}
result = requests.get("http://translate.google.cn/translate_a/single?client=t&sl=auto&tl=en&hl=en&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))
# 返回的結果爲Json,解析爲一個嵌套列表
trans = result.json()[0]
ret = ''
for i in range(len(trans)):
line = trans[i][0]
if line != None:
ret += trans[i][0]
return ret
問題與解析
1.No module named ‘execjs’
安裝execjs即可 pip install PyExecJS
2.部分原理介紹:
Py4Js.py:用於獲得tk。
打開google的瀏覽器,進入翻譯界面https://translate.google.cn/,打開開發者模式,觀察network,輸入翻譯內容進行測試,可以發現,帶有single?client=web…的url裏面有翻譯的結果:
可以看到翻譯結果在Response的第一個列表的第一個位置,所以實現翻譯只需要獲得此url並且獲取第一個位置的字符串即可。以下部分代碼就是實現獲得第一個列表第一個位置的字符串:
for i in range(len(trans)):
line = trans[i][0]
if line != None:
ret += trans[i][0]
關於tk:在google搜索上,基本上不同的翻譯內容對應着不同的tk值,而其他的比如翻譯語言、翻譯結構等參數都幾乎相同,比如China對應的tk是942592.574918。有大神破解了tk,即使用js生成對應文本的tk。也有根據node.js實現這個爬蟲的,可參考:https://segmentfault.com/a/1190000019152744?utm_source=tag-newest
關於不限字符翻譯,在此部分實現不限字符翻譯,即分段翻譯然後拼接起來:
if len(content)>4891:
while len(content) > 4891:
#print("翻譯的長度超過限制!!!")
temp=content[0:4000-len(content[0:4000].split('.')[-1])]+content[4000].split('.')[0]
content=content[4001-len(content[0:4000].split('.')[-1]):]
#temp=content[0:4889]
#content=content[4890:]
print(content+"\n\n")
temp_trans=google_trans_final(temp)
res_trans=res_trans+temp_trans
#google_translate(content)
print("實現多次翻譯拼接,用這個分割一下\n\n")
#return
其中4891是經過測試的谷歌穩定翻譯的最大字符數。但是此處翻譯還有很大的完善空間,對某些語言的翻譯效果不好。如果是翻譯很長的文本,需要對這部分進行完善,如有建議、改進措施歡迎評論和私信。