工具
python 库:1.tkinter,2.requests 3.execjs
废话不多说,我们直接上代码
代码
import requests
import execjs
import tkinter as tk
class BaiduFanyi:
def __init__(self):
self.headers = {
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1",
"cookie" : your cookie
self.get_type_url = "https://fanyi.baidu.com/langdetect"
self.get_tra_url = "https://fanyi.baidu.com/basetrans"
self.windows = tk.Tk()
self.windows.title("中英翻译")
self.windows.geometry("400x200") # 设置窗口大小
self.entry_tra = tk.Entry(self.windows, show=None,width = 100,fg = "red",relief = "groove", bd = 5) # 使输入的文本显示为*
# self.b2 = tk.Button(self.windows, text="点击识别语言", width=15, height=2,
# command=self.insert_point)
self.b1 = tk.Button(self.windows, text="点击翻译", width=15, height=2,
command=self.translate,bg = 'pink')
self.delete_button = tk.Button(self.windows,text = "清空文本框",width = 15,
height = 2,command = self.delete,bg = 'pink')
self.t = tk.Text(self.windows,height=3,font = 5)
# def insert_point(self):
# self.tra_str = self.entry_tra.get()
def parse_html(self, url, data):
r = requests.post(url, data=data, headers=self.headers)
return r.json()
def get_sign(self):
with open("baidujs.js") as f:
jsData = f.read()
sign = execjs.compile(jsData).call("e", self.tra_str)
return sign
def translate(self):
self.tra_str = self.entry_tra.get()
# 1.获取语言类型
types_data = {"query": self.tra_str}
re_json = self.parse_html(self.get_type_url, types_data)
type = re_json['lan']
# 2.准备翻译的post的data
sign = self.get_sign()
if type == "zh":
tra_data = {"query": self.tra_str, "from": "zh", "to": "en", "token": "dcad8163e70e68b45795c90114945ad0",
"sign": sign}
else:
tra_data = {"query": self.tra_str, "from": "en", "to": "zh", "token": "dcad8163e70e68b45795c90114945ad0",
"sign": sign}
# 3.发出请求
tra_json = self.parse_html(self.get_tra_url, tra_data)
result = tra_json['trans'][0]['result'][0][1]
self.t.insert("end",result)
def delete(self):
self.t.delete(0.0,tk.END)
def run(self):
self.entry_tra.pack() # 将输入框安放在窗口上
# self.b2.pack()
self.b1.pack() # 将b1放置在窗口上
self.t.pack() # 将接收文本框安放在窗口上
self.delete_button.pack() # 放置文本框清空按键
self.windows.mainloop() # 使窗口不断循环显示
def main():
baidu_fanyi = BaiduFanyi()
baidu_fanyi.run()
if __name__ == '__main__':
main()
思路
思路还是比较简单的,利用requests的post请求发送到百度翻译接口,然后用tkinter创建一个界面但有个问题是sign参数比较难解决,所以百度了下参考了https://blog.csdn.net/qq_30162859/article/details/82928770
记得cookie是要带的
效果
不足
①英译中时只能翻译短句子
②图形化界面比较简陋
③只能实现中英翻译