api.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. """
  2. 谷歌翻译接口
  3. """
  4. from urllib.parse import quote
  5. import requests
  6. import execjs
  7. import logging
  8. logger = logging.getLogger(__name__)
  9. code = """
  10. function TL(a) {
  11. var k = "";
  12. var b = 406644;
  13. var b1 = 3293161072;
  14. var jd = ".";
  15. var $b = "+-a^+6";
  16. var Zb = "+-3^+b+-f";
  17. for (var e = [], f = 0, g = 0; g < a.length; g++) {
  18. var m = a.charCodeAt(g);
  19. 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),
  20. e[f++] = m >> 18 | 240,
  21. e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224,
  22. e[f++] = m >> 6 & 63 | 128),
  23. e[f++] = m & 63 | 128)
  24. }
  25. a = b;
  26. for (f = 0; f < e.length; f++) a += e[f],
  27. a = RL(a, $b);
  28. a = RL(a, Zb);
  29. a ^= b1 || 0;
  30. 0 > a && (a = (a & 2147483647) + 2147483648);
  31. a %= 1E6;
  32. return a.toString() + jd + (a ^ b)
  33. };
  34. function RL(a, b) {
  35. var t = "a";
  36. var Yb = "+";
  37. for (var c = 0; c < b.length - 2; c += 3) {
  38. var d = b.charAt(c + 2),
  39. d = d >= t ? d.charCodeAt(0) - 87 : Number(d),
  40. d = b.charAt(c + 1) == Yb ? a >>> d: a << d;
  41. a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d
  42. }
  43. return a
  44. }
  45. """
  46. class Api(object):
  47. def __init__(self):
  48. self.ctx = execjs.compile(code)
  49. self.headers = {
  50. 'authority': 'translate.google.cn',
  51. 'method': 'GET',
  52. 'path': '',
  53. 'scheme': 'https',
  54. 'accept': '*/*',
  55. 'accept-encoding': 'gzip, deflate, br',
  56. 'accept-language': 'zh-CN,zh;q=0.9,ja;q=0.8',
  57. # 'cookie': '_ga=GA1.3.110668007.1547438795; _gid=GA1.3.791931751.1548053917; 1P_JAR=2019-1-23-1; NID=156=biJbQQ3j2gPAJVBfdgBjWHjpC5m9vPqwJ6n6gxTvY8n1eyM8LY5tkYDRsYvacEnWNtMh3ux0-lUJr439QFquSoqEIByw7al6n_yrHqhFNnb5fKyIWMewmqoOJ2fyNaZWrCwl7MA8P_qqPDM5uRIm9SAc5ybSGZijsjalN8YDkxQ',
  58. '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',
  59. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36',
  60. 'x-client-data': 'CKi1yQEIhrbJAQijtskBCMG2yQEIqZ3KAQioo8oBCL+nygEI7KfKAQjiqMoBGPmlygE='
  61. }
  62. def get_tk(self, text):
  63. return self.ctx.call("TL", text)
  64. @staticmethod
  65. def build_url(text, tk, tl='zh-CN'):
  66. """
  67. 需要用转URLEncoder
  68. :param text:
  69. :param tk:
  70. :param tl:
  71. :return:
  72. """
  73. 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')}"
  74. def translate(self, text, output_type='zh-CN'):
  75. """
  76. language_type为要翻译的语言
  77. de:德语
  78. ja:日语
  79. sv:瑞典语
  80. nl:荷兰语
  81. ar:阿拉伯语
  82. ko:韩语
  83. pt:葡萄牙语
  84. zh-CN:中文简体
  85. zh-TW:中文繁体
  86. """
  87. # url = 'https://translate.google.cn/translate_a/single'
  88. # data = {
  89. # 'client': 'webapp',
  90. # 'sl': 'auto',
  91. # 'tl': output_type,
  92. # 'hl': 'zh-CN',
  93. # 'dt': 'at',
  94. # 'source': 'btn',
  95. # 'ssel': '0',
  96. # 'tsel': '0',
  97. # 'kc': '0',
  98. # 'tk': self.get_tk(text),
  99. # 'q': quote(text, encoding='utf-8'),
  100. # }
  101. url = self.build_url(text, self.get_tk(text), output_type)
  102. try:
  103. logger.info(f"GoogleApi.translate:request: {url}")
  104. # response = requests.get(url=url, headers=self.headers, params=data)
  105. response = requests.get(url=url, headers=self.headers)
  106. logger.info(f"GoogleApi.translate:response: {response.status_code}")
  107. except Exception as e:
  108. import traceback
  109. logger.info(f"GoogleApi.translate:error: {e.__class__.__name__}")
  110. logger.info(f"GoogleApi.translate:details: {traceback.format_exc()}")
  111. return ''
  112. if response.status_code > 300:
  113. logger.info(f"GoogleApi.translate:status: {response.status_code}")
  114. logger.info(f"GoogleApi.translate:reason: {response.reason}")
  115. logger.info(f"GoogleApi.translate:result: {response.text}")
  116. return ''
  117. else:
  118. return response.json()[0][0][0]
  119. if __name__ == '__main__':
  120. 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.'
  121. api = Api()
  122. translate_result = api.translate(word)
  123. print(translate_result)