python3实现简单的google翻译调用,第二版
https://download.csdn.net/download/weixin_42152696/10646652
手把手教你调google翻译接口,旁的话不多说,直接上重点内容。
注意几点:使用之前先安装第三方库,还有一个,def get_tk(text,tkk=‘426538.4063001528’) 这里面的kk值请自行做计算,根据我之前使用的情况来看,这个值基本上不会发生变动,对于这个kk值,我这里不再多做叙述,我只提供最好用的实战部分。
# -*- coding: utf-8 -*-
import execjs
import requests
import json
import urllib3.contrib.pyopenssl
#----------------------------------
#这里的tkk值需要进行后期喜欢,需要根据tkk.js这个文件进行计算操作,具体的计算请使用node js去进行,命令行就能搞定
def get_tk(text,tkk='426538.4063001528'):
jsstr = get_js()
ctx = execjs.compile(jsstr) #加载JS文件
return (ctx.call('tk',text,tkk)) #调用js方法 第一个参数是JS的方法名,后面的data和key是js方法的参数
def get_js():
f = open("tk.js", 'r', encoding='utf-8') # 打开JS文件
line = f.readline()
htmlstr = ''
while line:
htmlstr = htmlstr+line
line = f.readline()
return htmlstr
def write_txt(file_name,info):
fp = open(file_name, "a",encoding='utf-8') # 打开一个文本文件
fp.write(info+'\n') # 写入数据
fp.close() # 关闭文件
def google_tran(from_lang, to_lang, tran_text):
tk = get_tk(tran_text)
url = "https://translate.google.cn/translate_a/single?client=t&sl=" + from_lang + "&tl=" + to_lang + "&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=" + tk + "&q=" + tran_text
file_name = "tran.txt"
txt_file_path = file_name
# requests.packages.urllib3.disable_warnings()
# r = requests.get(url ,verify=False ,headers={'Connection':'close'})
# requests.adapters.DEFAULT_RETRIES = 5
# s = requests.session()
# s.keep_alive = False
#免费代理使用网站
#http://ip.zdaye.com/shanghai_ip.html#Free
s = requests.session()
# url = "https://mail.163.com/"
s.keep_alive = False
#这里写的是代理,自主去发挥内容
#s.proxies = {"http": "ip:端口" }
s.headers = {'Connection':'close'}
r = s.get(url)
with open(txt_file_path, "wb") as code:
code.write(r.content)
try:
byte_to_string = str(r.content, encoding="utf-8")
string_to_list = json.loads(byte_to_string)
return string_to_list
except Exception as e:
print(e)
return ""
'''
调用范例:
from_lang = "zh-CN"
to_lang = "en"
tran_text = "大家好"
result = google_tran(from_lang, to_lang, tran_text)
print(len(result))
print(result[0][0][0])
print('ok')
en 英语
tr 土语
uz 乌语
'''
if __name__ == '__main__':
from_lang = "zh-CN"
to_lang = "uz"
tran_text = "你好"
result = google_tran(from_lang, to_lang, tran_text)
print(len(result))
print(result[0][0][0])
print('ok')