基于上次写的有道翻译程序python实战:利用chrome抓包插件HTTP间谍分析有道翻译反爬机制,此次我们使用tkinter模块创建可视化界面,并将.py程序转化成.exe可执行文件。
**1、**首先我们需下载pyInstaller,pyInstaller的下载地址为 http://www.pyinstaller.org/downloads.html (看好自己python的版本进行下载),建议下载并解压后和python放在相同的目录下:
此外,我们还需要下载一个pywin32,pywin32的下载地址为:https://sourceforge.net/projects/pywin32/files/pywin32/Build 221/ (看好自己python的版本进行下载)。
2、安装pyInstaller和pywin32:
**3、**在之前写的有道翻译程序python实战:利用chrome抓包插件HTTP间谍分析有道翻译反爬机制中我们进行相应的修改,代码改为:
youdao_UI.py:
from tkinter import *
import js2py
import hashlib
import time,random,requests
def set_user_agent():
USER_AGENTS = [
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
"Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
"Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
"Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5"
]
user_agent = random.choice(USER_AGENTS)
return user_agent
js_str = """r = "" + (new Date).getTime()
, i = r + parseInt(10 * Math.random(), 10);"""
js_text = js2py.EvalJs()
js_text.execute(js_str)
def getSalt():
# salt的公式r = "" + ((new Date).getTime() + parseInt(10 * Math.random(), 10))
# 方法1:利用js2py模块,获取salt值:
# salt_text = js2py.EvalJs()
# js_str = """r = "" + (new Date).getTime()
# , i = r + parseInt(10 * Math.random(), 10);"""
# salt_text.execute(js_str)
salt = js_text.i
# 方法2:将js_str翻译成python代码获取salt值:
# salt = int(time.time()*1000) + random.randint(0, 10)
return salt
def getMd5(text):
if not isinstance(text, bytes):
text = bytes(text, 'utf-8')
m = hashlib.md5()
m.update(text)
return m.hexdigest()
# 定义App类表示应用/窗口,继承Frame类
class App(Frame):
# App构造函数,master为窗口的父控件
def __init__(self, master=None):
Frame.__init__(self, master)# 初始化App的Frame部分
self.pack()
# welcome image
self.canvas = Canvas(self, height=210, width=500)
self.image_file = PhotoImage(file='youdao.gif')
self.canvas.create_image(0, 0, anchor='nw', image=self.image_file)
self.canvas.pack(side='top')
# user information
self.label_text= Label(self, text="请输入要翻译内容后点击翻译")
self.label_text.pack()
self.label_WORD = Label(self, text="待译内容:").place(x=5, y= 260)
self.entry_contents_WORD =Text(self,width=40,height=5)
self.entry_contents_WORD.pack() # 将文本框放置到主窗口中
self.label_RESULT = Label(self, text="结果提示:").place(x=5, y=330)
self.entry_contents_RESULT = Text(self, width=40, height=5)
self.entry_contents_RESULT.pack()
# 创建一个'翻译'按钮,点击会执行download函数
self.button1 = Button(self, text="翻译",command=self.translate)
self.button1.pack(side=LEFT,expand=YES, fill=X)
# 创建一个'清空'按钮,点击会执行clear函数
self.button2 = Button(self, text="清空", command=self.clear)
self.button2.pack(side=RIGHT,expand=YES, fill=X)
self.headers = {
"Accept": "application/json,text/javascript,*/*;q=0.01",
"Accept-Encoding": "gzip,deflate",
"Accept-Language": "zh-CN,zh;q=0.9",
"Connection": "keep-alive",
"Host": "fanyi.youdao.com",
"Origin": "http://fanyi.youdao.com",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
'User-Agent': set_user_agent(),
'Referer': 'http://fanyi.youdao.com/',
'Cookie': '[email protected]; JSESSIONID=aaaBADMLwT0Wj8je4pjKw; OUTFOX_SEARCH_USER_ID_NCOO=1012727192.8548353; YOUDAO_MOBILE_ACCESS_TYPE=0; DICT_UGC=be3af0da19b5c5e6aa4e17bd8d90b28a|; JSESSIONID=abcVeHVPsZKjL9bo6tjKw; user-from=http://www.youdao.com/; from-page=http://www.youdao.com/; ___rl__test__cookies=1550646069714'
}
self.data = {
'i': None,
"from": "AUTO",
"to": "AUTO",
"smartresult": "dict",
'client': 'fanyideskweb',
'keyfrom': 'fanyi.web',
"doctype": "json",
"version": "2.1",
"action": "FY_BY_CLICKBUTTION",
"typoResult": "false",
"bv": getMd5(set_user_agent()),
"ts": js_text.r,
'salt': None,
'sign': None
}
self.url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
def clear(self):
self.entry_contents_WORD.delete(0.0, END)
self.entry_contents_RESULT.delete(0.0, END)
def getSign(self):
keyword=self.entry_contents_WORD.get("0.0", "end")
salt=getSalt()
sign = "fanyideskweb" + keyword + str(salt) + "p09@Bn{h02_BIEe]$P^nG"
sign = getMd5(sign)
return sign
def translate(self):
self.data['i'] = self.entry_contents_WORD.get("0.0", "end")
self.data['salt'] = getSalt()
self.data['sign'] = self.getSign()
res = requests.post(self.url, headers=self.headers, data=self.data)
result=res.json()['translateResult'][0][0]['tgt']
self.entry_contents_RESULT.delete(0.0, END)
self.entry_contents_RESULT.insert(INSERT, result)
root = App()#创建一个名为root的App对象
window=root.master
window.title("局长出品")#设置窗口的标题
window.geometry('400x410')
window.wm_resizable(False, False)#不允许改变窗口的宽和高
root.mainloop()#进入主循环
这是修改后得到的可视化界面:
**4、**制作exe文件:将youdao_UI.py及背景图youdao.gif(必须是gif格式)放到pyinstaller-pyinstaller目录下, 在该目录下打开CMD命令(按shift+鼠标右键在此处打开命令窗口)执行:python pyinstaller.py -F youdao_UI.py。命令完成后会在该目录下生成一个youdao_UI文件夹,按下图路径进入就能得到我们的youdao_UI.exe文件(此时要想正常执行该文件仍需要将youdao.gif放在该目录下)。