脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 告别网页搜索!教你用python实现一款属于自己的翻译词典软件

告别网页搜索!教你用python实现一款属于自己的翻译词典软件

2021-11-22 10:27武亮宇 Python

教你用python做一款属于自己的翻译词典软件,从此告别网页搜索,文中有非常详细的代码示例,小伙伴们快快行动吧,需要的朋友可以参考下

一、设计理念

1.先写一个登录的py文件,用python的tkinter库
2.再写一个py文件用于爬取有道翻译输出栏的内容
3.再利用python的tkinter库,完成软件运行的窗口
4.将窗口的返回值与爬取有道翻译的结果接口对一下
5.第二个py文件里import第一个py文件,两个文件相关联

二、代码解析

请求方式为post,要注意from data里的值,这里可以在网页上再输一个想要翻译的内容,观察from data里的值的变化,可以确定'salt'、 ‘sign'、 'lts'这三个值变化
进入网页源代码搜索.js,找到对应的js文件,找到他们的加密规则,最后将获得的response转化为字典,提取结果

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class YouDao(object):
    a.LoginPage()
    def __init__(self):
        pass
 
    def crawl(self, content):
        # 进入网页源代码搜索.js  点击进入搜索看是否有'salt''sign''lts'这三个 有则证明找的文件正确 全部复制 网页搜js格式化转化  创建js文件
        lts = int(time.time() * 1000)    # 时间戳转化为毫秒    时间戳转化为时间 站长工具
        timestamp = lts + random.randint(0, 10)
        # sign: n.md5("fanyideskweb" + e + i + "Tbh5E8=q6U3EXe+&L[4c@")
 
        a = "fanyideskweb"
        e = content
        i = str(timestamp)
        d = "Tbh5E8=q6U3EXe+&L[4c@"
        sign = hashlib.md5((a+e+i+d).encode('utf-8')).hexdigest()
        data = {
            'i': content,
            'from': 'AUTO',
            'to': 'AUTO',
            'smartresult': 'dict',
            'client': 'fanyideskweb',
            'salt': timestamp,
            'sign': sign,
            'lts': lts,
            'bv': 'dd67d51c2bbb03cccdbcfa48735ba27f',
            'doctype': 'json',
            'version': '2.1',
            'keyfrom': 'fanyi.web',
            'action': 'FY_BY_CLICKBUTTION'
        }
        data = urllib.parse.urlencode(data).encode('utf-8')
        headers = {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36',
                    'Cookie': 'OUTFOX_SEARCH_USER_ID=406040753@221.204.120.171; DICT_UGC=be3af0da19b5c5e6aa4e17bd8d90b28a|; JSESSIONID=abcJcdIfpYuE3eNgyi3Dx; OUTFOX_SEARCH_USER_ID_NCOO=902501357.1460881; user-from=http://www.youdao.com/; from-page=http://www.youdao.com/; _ntes_nnid=250706e8175b6796101a34821527eb62,1612611490655; DICT_SESS=v2|qKlfGGGmbVOAOfp40fQy0UWhfPuOMzWRlfk4Qz0LYERTu0flfn4Ul0l50He40fOW0TK6LlWRf6B0w46LYmh46F0JShMTLOfOm0; DICT_LOGIN=1||1612612510172; STUDY_SESS=EtwvT8KhyXqnLv8r0zdde8FcMOICmtZSIsltEiKZiAQq44wPVNN6PupszWYKIkBKfygQdvKlXU7p3aF+p0H6VcZLod3s2Bld6H/EWIphmRS92qG/3vVhSxHFAXq2yJp8QyH/R6RElNstKdVewVkZp+NyGWhzlamzU5dl6aBiyQ2Ybdo8MpdaPQB26wR6JPAU+P6MxCmnJEvne6pPMc9TTJJnThNrM7aj0X5LVpSBvjZ0h3M1drl4ZsmtkumIhrpyk1pBNevj8UEmS52Cj8DFo+yez89Xrbg4rxsvfSmuH21KlOh/Gwx6G1S/X4FQ7qd/Z2lDsk6Qgl21Md/1bCxa/orloi9qObM4N2yVCVhvkDdg5ILQezB8iskCpUa+ESZk; STUDY_INFO=UID_10AE81F6EF9DD9807BAC3FF3FD6407BA|4|1456638755|1612612364854; ___rl__test__cookies=1612663596564',
                    'Referer': 'http://fanyi.youdao.com/',
                }
        request = urllib.request.Request('http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule',
                                         method='POST', data=data, headers=headers)
        response = urllib.request.urlopen(request)
        result_str = response.read().decode('utf-8')
        result_dict = json.loads(result_str)
        result = result_dict["translateResult"][0][0]["tgt"]
        return result

三、软件窗口界面

尤其注意按钮这个地方

self.button = Button(self.window, text=u'查询', command=self.function)
command命令执行function

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Application(object):
    def __init__(self):
        # 创建一个窗口
        self.window = Tk()
        # 窗口标题
        self.window.title(u'武亮宇翻译词典')
        # 设置窗口大小位置
        self.window.geometry("280x350+400+150")
        # 输入框
        self.entry = Entry(self.window)
        self.entry.place(x=10, y=10, width=200, height=25# width=宽度, height=高度
        # 查询按钮
        self.button = Button(self.window, text=u'查询', command=self.function)        # command执行命令的意思 执行这个函数
        self.button.place(x=220, y=10, width=50, height=25)
        # 翻译结果标题
        self.label = Label(self.window, text=u'翻译结果:')
        self.label.place(x=10, y=45)
        # 翻译框
        self.text = Text(self.window, background='#ccc')           # 设置背景颜色
        self.text.place(x=10, y=75, width=260, height=265)

function这块要把爬虫返回的值和窗口的翻译框做一下接口

?
1
2
3
4
5
6
7
8
9
def function(self):
        # 从输入框中获取用户的值
        content = self.entry.get()
        # 把值发送给有道服务器进行翻译
        youdao = YouDao()
        result = youdao.crawl(content)
        # 把结果放在翻译框里
        self.text.delete(1.0, END)      # 每次查询先删除一下
        self.text.insert(END, result)   # 插入文本最后的位置 导入END库

四、源码展示

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import urllib.request     # 发送网络请求
import urllib.parse        # 参数解析
import time
import random
import hashlib
import json
from tkinter import Tk, Entry, Button, Label, Text, END  # Tk(创建窗口), Entry(输入框), Button(按钮), Label(标签), Text(文本框),
# END
import a
 
class YouDao(object):
    a.LoginPage()
    def __init__(self):
        pass
 
    def crawl(self, content):
        # 进入网页源代码搜索.js  点击进入搜索看是否有'salt''sign''lts'这三个 有则证明找的文件正确 全部复制 网页搜js格式化转化  创建js文件
        lts = int(time.time() * 1000)    # 时间戳转化为毫秒    时间戳转化为时间 站长工具
        timestamp = lts + random.randint(0, 10)
        # sign: n.md5("fanyideskweb" + e + i + "Tbh5E8=q6U3EXe+&L[4c@")
 
        a = "fanyideskweb"
        e = content
        i = str(timestamp)
        d = "Tbh5E8=q6U3EXe+&L[4c@"
        sign = hashlib.md5((a+e+i+d).encode('utf-8')).hexdigest()
        data = {
            'i': content,
            'from': 'AUTO',
            'to': 'AUTO',
            'smartresult': 'dict',
            'client': 'fanyideskweb',
            'salt': timestamp,
            'sign': sign,
            'lts': lts,
            'bv': 'dd67d51c2bbb03cccdbcfa48735ba27f',
            'doctype': 'json',
            'version': '2.1',
            'keyfrom': 'fanyi.web',
            'action': 'FY_BY_CLICKBUTTION'
        }
        data = urllib.parse.urlencode(data).encode('utf-8')
        headers = {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36',
                    'Cookie': 'OUTFOX_SEARCH_USER_ID=406040753@221.204.120.171; DICT_UGC=be3af0da19b5c5e6aa4e17bd8d90b28a|; JSESSIONID=abcJcdIfpYuE3eNgyi3Dx; OUTFOX_SEARCH_USER_ID_NCOO=902501357.1460881; user-from=http://www.youdao.com/; from-page=http://www.youdao.com/; _ntes_nnid=250706e8175b6796101a34821527eb62,1612611490655; DICT_SESS=v2|qKlfGGGmbVOAOfp40fQy0UWhfPuOMzWRlfk4Qz0LYERTu0flfn4Ul0l50He40fOW0TK6LlWRf6B0w46LYmh46F0JShMTLOfOm0; DICT_LOGIN=1||1612612510172; STUDY_SESS=EtwvT8KhyXqnLv8r0zdde8FcMOICmtZSIsltEiKZiAQq44wPVNN6PupszWYKIkBKfygQdvKlXU7p3aF+p0H6VcZLod3s2Bld6H/EWIphmRS92qG/3vVhSxHFAXq2yJp8QyH/R6RElNstKdVewVkZp+NyGWhzlamzU5dl6aBiyQ2Ybdo8MpdaPQB26wR6JPAU+P6MxCmnJEvne6pPMc9TTJJnThNrM7aj0X5LVpSBvjZ0h3M1drl4ZsmtkumIhrpyk1pBNevj8UEmS52Cj8DFo+yez89Xrbg4rxsvfSmuH21KlOh/Gwx6G1S/X4FQ7qd/Z2lDsk6Qgl21Md/1bCxa/orloi9qObM4N2yVCVhvkDdg5ILQezB8iskCpUa+ESZk; STUDY_INFO=UID_10AE81F6EF9DD9807BAC3FF3FD6407BA|4|1456638755|1612612364854; ___rl__test__cookies=1612663596564',
                    'Referer': 'http://fanyi.youdao.com/',
                }
        request = urllib.request.Request('http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule',
                                         method='POST', data=data, headers=headers)
        response = urllib.request.urlopen(request)
        result_str = response.read().decode('utf-8')
        result_dict = json.loads(result_str)
        result = result_dict["translateResult"][0][0]["tgt"]
        return result
 
 
class Application(object):
    def __init__(self):
        # 创建一个窗口
        self.window = Tk()
        # 窗口标题
        self.window.title(u'武亮宇翻译词典')
        # 设置窗口大小位置
        self.window.geometry("280x350+400+150")
        # 输入框
        self.entry = Entry(self.window)
        self.entry.place(x=10, y=10, width=200, height=25# width=宽度, height=高度
        # 查询按钮
        self.button = Button(self.window, text=u'查询', command=self.function)        # command执行命令的意思 执行这个函数
        self.button.place(x=220, y=10, width=50, height=25)
        # 翻译结果标题
        self.label = Label(self.window, text=u'翻译结果:')
        self.label.place(x=10, y=45)
        # 翻译框
        self.text = Text(self.window, background='#ccc')           # 设置背景颜色
        self.text.place(x=10, y=75, width=260, height=265)
 
    def function(self):
        # 从输入框中获取用户的值
        content = self.entry.get()
        # 把值发送给有道服务器进行翻译
        youdao = YouDao()
        result = youdao.crawl(content)
        # 把结果放在翻译框里
        self.text.delete(1.0, END)      # 每次查询先删除一下
        self.text.insert(END, result)   # 插入文本最后的位置 导入END库
 
    def run(self):
        self.window.mainloop()
 
 
if __name__ == '__main__':
    app = Application()
    app.run()
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# !/usr/bin/nev python
# -*-coding:utf8-*-
import tkinter
import tkinter.messagebox
class LoginPage(object):
    def __init__(self):
        #声明两个变量
        self.win = tkinter.Tk()  # 窗口
        self.username = tkinter.StringVar()
        self.password = tkinter.StringVar()
        self.n=2
        self.createForm()
    def login(self):
        if self.username.get()=='新星计划' and self.password.get()=='新星计划':
            print('登录成功')
            tkinter.messagebox.showinfo(title='登录信息',message='登录成功')
            self.win.quit()
        elif self.n==0:
            print('你没有权限进入该系统')
            self.win.quit()
        else:
            print('登录失败')
            print('账号或密码错误,你还有%d次机会'%self.n)
            tkinter.messagebox.showerror(title='登录信息',message='登录失败')
        self.n-=1
    def createForm(self):
        self.win.title('登录界面')
        self.win.geometry("280x200+400+150")
        #创建标签
        labelname = tkinter.Label(self.win,text='用户名:',justify=tkinter.RIGHT,width = 100)
        labelname.place(x=35,y=50,width=80,height=20)
        #创建文本框
        entryname = tkinter.Entry(self.win, width=150, textvariable=self.username)
        entryname.place(x=110, y=50, width=120, height=20)
        #创建密码标签
        labelpwd = tkinter.Label(self.win,text='密  码:', justify=tkinter.RIGHT,width=80)
        labelpwd.place(x=35, y=80, width=80, height=20)
        #创建密码的文本框
        entrypwd = tkinter.Entry(self.win, width=150,textvariable=self.password)
        entrypwd.place(x=110, y=80, width=120, height=20)
        #创建button按钮
        buttonOk = tkinter.Button(self.win,text='登录',command=self.login)
        buttonOk.place(x=95,y=130,width=50,height=20)
        #创建退出的按钮
        buttonQuit = tkinter.Button(self.win,text='退出',command=self.win.quit)
        buttonQuit.place(x=145,y=130,width=50,height=20)
        self.win.mainloop()
if __name__ == '__main__':
    lg = LoginPage()

一共两个py文件,赶快收藏啊,快去试试吧,能拥有自己的翻译词典!!!

五、效果展示

先看一下软件效果,先登录

告别网页搜索!教你用python实现一款属于自己的翻译词典软件

各种语言都可以转换

告别网页搜索!教你用python实现一款属于自己的翻译词典软件

到此这篇关于告别网页搜索!教你用python实现一款属于自己的翻译词典软件的文章就介绍到这了,更多相关python翻译词典软件内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_54733110/article/details/117449191

延伸 · 阅读

精彩推荐