123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- """
- 谷歌翻译接口
- """
- from urllib.parse import quote
- import requests
- import execjs
- import logging
- logger = logging.getLogger(__name__)
- code = """
- 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
- }
- """
- class Api(object):
- def __init__(self):
- self.ctx = execjs.compile(code)
- self.headers = {
- 'authority': 'translate.google.cn',
- 'method': 'GET',
- 'path': '',
- 'scheme': 'https',
- 'accept': '*/*',
- 'accept-encoding': 'gzip, deflate, br',
- 'accept-language': 'zh-CN,zh;q=0.9,ja;q=0.8',
- # 'cookie': '_ga=GA1.3.110668007.1547438795; _gid=GA1.3.791931751.1548053917; 1P_JAR=2019-1-23-1; NID=156=biJbQQ3j2gPAJVBfdgBjWHjpC5m9vPqwJ6n6gxTvY8n1eyM8LY5tkYDRsYvacEnWNtMh3ux0-lUJr439QFquSoqEIByw7al6n_yrHqhFNnb5fKyIWMewmqoOJ2fyNaZWrCwl7MA8P_qqPDM5uRIm9SAc5ybSGZijsjalN8YDkxQ',
- 'cookie': '_ga=GA1.3.110668007.1547438795; _gid=GA1.3.1522575542.1548327032; 1P_JAR=2019-1-24-10; NID=156=ELGmtJHel1YG9Q3RxRI4HTgAc3l1n7Y6PAxGwvecTJDJ2ScgW2p-CXdvh88XFb9dTbYEBkoayWb-2vjJbB-Rhf6auRj-M-2QRUKdZG04lt7ybh8GgffGtepoA4oPN9OO9TeAoWDY0HJHDWCUwCpYzlaQK-gKCh5aVC4HVMeoppI',
- 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36',
- 'x-client-data': 'CKi1yQEIhrbJAQijtskBCMG2yQEIqZ3KAQioo8oBCL+nygEI7KfKAQjiqMoBGPmlygE='
- }
- def get_tk(self, text):
- return self.ctx.call("TL", text)
- @staticmethod
- def build_url(text, tk, tl='zh-CN'):
- """
- 需要用转URLEncoder
- :param text:
- :param tk:
- :param tl:
- :return:
- """
- return f"https://translate.google.cn/translate_a/single?client=webapp&sl=auto&tl={tl}&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&source=btn&ssel=0&tsel=0&kc=0&tk={tk}&q={quote(text, encoding='utf-8')}"
- def translate(self, text, output_type='zh-CN'):
- """
- language_type为要翻译的语言
- de:德语
- ja:日语
- sv:瑞典语
- nl:荷兰语
- ar:阿拉伯语
- ko:韩语
- pt:葡萄牙语
- zh-CN:中文简体
- zh-TW:中文繁体
- """
- # url = 'https://translate.google.cn/translate_a/single'
- # data = {
- # 'client': 'webapp',
- # 'sl': 'auto',
- # 'tl': output_type,
- # 'hl': 'zh-CN',
- # 'dt': 'at',
- # 'source': 'btn',
- # 'ssel': '0',
- # 'tsel': '0',
- # 'kc': '0',
- # 'tk': self.get_tk(text),
- # 'q': quote(text, encoding='utf-8'),
- # }
- url = self.build_url(text, self.get_tk(text), output_type)
- try:
- logger.info(f"GoogleApi.translate:request: {url}")
- # response = requests.get(url=url, headers=self.headers, params=data)
- response = requests.get(url=url, headers=self.headers)
- logger.info(f"GoogleApi.translate:response: {response.status_code}")
- except Exception as e:
- import traceback
- logger.info(f"GoogleApi.translate:error: {e.__class__.__name__}")
- logger.info(f"GoogleApi.translate:details: {traceback.format_exc()}")
- return ''
- if response.status_code > 300:
- logger.info(f"GoogleApi.translate:status: {response.status_code}")
- logger.info(f"GoogleApi.translate:reason: {response.reason}")
- logger.info(f"GoogleApi.translate:result: {response.text}")
- return ''
- else:
- return response.json()[0][0][0]
- if __name__ == '__main__':
- word = '** RESERVED ** This candidate has been reserved by an organization or individual that will use it when announcing a new security problem. When the candidate has been publicized, the details for this candidate will be provided.'
- api = Api()
- translate_result = api.translate(word)
- print(translate_result)
|