python爬取实现自动翻译

爬取翻译的例子一搜一大把,看了好多例子,我也来跟风一波,就是瞎弄着玩的。
最终实现结果:

python爬取实现自动翻译

完整代码:

import urllib.request
import urllib.parse
import json
from tkinter import *
root=Tk()
root.title("我爱英语;信你个鬼!")
sw = root.winfo_screenwidth()
#得到屏幕宽度
sh = root.winfo_screenheight()
#得到屏幕高度
ww = 500
wh = 300
x = (sw-ww) / 2
y = (sh-wh) / 2-50
root.geometry("%dx%d+%d+%d" %(ww,wh,x,y))
lb2=Label(root,text="输入英文翻译中文,或者输入中文翻译英文,按回车键翻译")
lb2.place(relx=0, rely=0.05)
txt = Text(root,font=("宋体",20))
txt.place(rely=0.6, relheight=0.4,relwidth=1)
inp1 = Entry(root,font=("",20))
inp1.place(relx=0, rely=0.2, relwidth=1, relheight=0.25)
def run2(event):
    txt.delete("0.0",END)
    a = (inp1.get())
    content = a
    url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
    data={}
    data['i'] = content
    data['from'] = 'AUTO'
    data['to'] = 'AUTO'
    data['smartresult'] = 'dict'
    data['client'] = 'fanyideskweb'
    data['salt'] = '15812376682056'
    data['sign'] = 'a1246b257926af8432be022564ff79f5'
    data['ts'] = '1581237668205'
    data['bv'] = '656f750600466990f874a839d9f5ad23'
    data['doctype'] = 'json'
    data['version'] = '2.1'
    data['keyfrom'] = 'fanyi.web'
    data['action'] = 'FY_BY_CLICKBUTTION'
    data = urllib.parse.urlencode(data).encode('utf-8')
    response = urllib.request.urlopen(url,data)
    html = response.read().decode('utf-8')
    target = json.loads(html)
    s=("%s"%(target['translateResult'][0][0]['tgt'])+"\n")
    print(s)
    txt.insert(END, s)   
def button1(event):
    btn1 = Button(root, text='翻译', font=("",12),command=run1)
    btn1.place(relx=0.35, rely=0.45, relwidth=0.2, relheight=0.15)
inp1.bind("<Return>",run2)
button1(1)
root.mainloop()

为了方便使用,将python程序打包成可执行文件,不再依赖编程环境,在cmd命令中执行

pyinstaller -F -w D:\python_test.py

-w后面跟着你的代码路径。
执行后dist目录中出现了python_test.exe文件。

pyinstaller 安装方法:https://blog.csdn.net/qq_45874897/article/details/106516400

上一篇:Python02_爬虫请求模块


下一篇:Python爬取有道词典,有道的反爬很难吗?也就这样啊!