|
发表于 2020-10-26 10:34:19
|
显示全部楼层
根据小甲鱼的有道翻译爬虫做了一个简单的tkinter界面:
from tkinter import *
import urllib.request
import urllib.parse
import json
import socket
#判断是否连接网络
def isNetOK():
s=socket.socket()
s.settimeout(3)
try:
status = s.connect_ex(('www.baidu.com',443))
if status == 0:
s.close()
return True
else:
return False
except Exception as e:
return False
#生成窗口及输入框
master=Tk()
master.title('Translation')
master.geometry("+500+300")
e1=Entry(master,width=50,font=('微软雅黑',12))
e1.grid(row=0,column=0,columnspan=3,padx=10,pady=5)
e2=Entry(master,width=50,font=('微软雅黑',12))
e2.grid(row=2,column=0,columnspan=3,padx=10,pady=5)
#判断是否连接网络并进行翻译
def tran():
e=isNetOK()
if not e:
e2.delete(0,END)
e2.insert(0,'未连接网络!')
else:
content=e1.get()
url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
head={}
head['User-Agent']='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'
data={}
data['i']= content
data['from']= 'AUTO'
data['to']= 'AUTO'
data['smartresult']= 'dict'
data['client']= 'fanyideskweb'
data['salt']= '16030968822001'
data['sign']= '3d19a464aaeb7e4703f0970aa5a001ef'
data['lts']: '1603096882200'
data['bv']= '7cdcc6da51be36f1eb381595522425c1'
data['doctype']= 'json'
data['version']= '2.1'
data['keyfrom']= 'fanyi.web'
data['action']= 'FY_BY_CLICKBUTTION'
data=urllib.parse.urlencode(data).encode('utf-8')
res=urllib.request.urlopen(url,data)
html = res.read().decode('utf-8')
tag=json.loads(html)
jieguo=tag['translateResult'][0][0]['tgt']
e2.delete(0,END)
e2.insert(0,jieguo)
#翻译快捷键函数
def tran_fun(self):
tran()
#清空函数
def clear():
e1.delete(0,END)
e2.delete(0,END)
#生成按钮
B1=Button(master,text='翻译(Enter)',font=('微软雅黑',12),width=10,command=tran).grid(row=1,column=0,\
padx=10)
e1.bind('<Return>',tran_fun) #定义翻译快捷键
B2=Button(master,text='退出',font=('微软雅黑',12),width=10,command=master.destroy).grid(row=1,column=2,\
padx=10)
B3=Button(master,text='清空',font=('微软雅黑',12),width=10,command=clear).grid(row=1,column=1)
mainloop()
|
|