forked from PantsuDango/Dango-Translator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Google.py
101 lines (74 loc) · 2.82 KB
/
Google.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# -*- coding:utf-8 -*-
import urllib.request
import urllib.parse
from requests import Session
from traceback import print_exc
from js2py import EvalJs
class GoogleTranslate():
def __init__(self):
self.headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'}
self.session = Session()
self.session.keep_alive = False
def getTk(self, text):
with open('.\\config\\GoogleJS.js', encoding='utf8') as f:
js_data = f.read()
context = EvalJs()
context.execute(js_data)
tk = context.TL(text)
return tk
def buildUrl(self, text ,tk):
baseUrl = 'http://translate.google.cn/translate_a/single'
baseUrl += '?client=webapp&'
baseUrl += 'sl=auto&'
baseUrl += 'tl=' + 'zh-CN' + '&'
baseUrl += 'hl=zh-CN&'
baseUrl += 'dt=at&'
baseUrl += 'dt=bd&'
baseUrl += 'dt=ex&'
baseUrl += 'dt=ld&'
baseUrl += 'dt=md&'
baseUrl += 'dt=qca&'
baseUrl += 'dt=rw&'
baseUrl += 'dt=rm&'
baseUrl += 'dt=ss&'
baseUrl += 'dt=t&'
baseUrl += 'ie=UTF-8&'
baseUrl += 'oe=UTF-8&'
baseUrl += 'clearbtn=1&'
baseUrl += 'otf=1&'
baseUrl += 'pc=1&'
baseUrl += 'srcrom=0&'
baseUrl += 'ssel=0&'
baseUrl += 'tsel=0&'
baseUrl += 'kc=2&'
baseUrl += 'tk=' + str(tk) + '&'
content = urllib.parse.quote(text)
baseUrl += 'q=' + content
return baseUrl
def getHtml(self, session, url, headers):
try:
html = session.get(url, headers=headers)
return html.json()
except Exception:
print_exc()
return None
def translate(self, text):
tk = self.getTk(text)
url = self.buildUrl(text, tk)
try:
result = self.getHtml(self.session, url, self.headers)
if result != None:
sentence = ''
for i in result[0]:
if i[0] != None:
sentence += i[0]
else:
sentence = "谷歌:我抽风啦!"
except Exception:
print_exc()
sentence = "谷歌:我抽风啦!"
return sentence
if __name__ == '__main__':
text = "そうすると、可笑しいことや変なこと、滑稽なことや正しくないこと、反対にやるべきことが见えてくるから。とにかく、何かにどっぷりはまっていると、周りのことが见えなくなってしまう。だから、时々一歩引くと物事が见えてくる。"
google = GoogleTranslate()
print(google.translate(text))