一、设计思路
百度翻译开放平台提供免费的API,为使用者提供高质量免费的翻译服务,我们可以申请成为开发者便可以调用百度翻译API编写一个小的翻译程序。其开发平台提供了详细的接入文档,按照文档要求,生成URL请求网页,提交后可返回JSON数据格式的翻译结果,再将得到的JSON格式的翻译结果解析出来即可。
二、具体操作
1、urllib库的模块
urllib库是Python标准库中最常用的Python网页访问模块,可以让用户像访问本地文本文件一样读取网页内容,常用模块包括:
- urllib.request:用来打开和读取url
- urllib.error:包含一些由urllib.request产生的错误,可以使用try进行捕捉处理
- urllib.parse:一些解析url的方法
- urllib.robotparser:解析rotbots.txt文本文件
2、urllib库的使用
I.获取网页信息: urllib使用request.urlopen()打开和读取URL信息,返回的对象Response如同一个文本对象,可以通过调用read()进行读取,再通过print()将读取的信息打印出来
part 1
from urllib import request
if __name__ == '__main__':
'''
urllib使用request.urlopen()打开和读取URL信息,返回的对象Response如同一个文本对象,可以通过调用read()进行读取,
在通过print()将读取的信息打印出来
查看网页的编码方式,查看网页源代码找到head标签开始位置的chareset,可以看到网页的编码方式
'''
reponse = request.urlopen("https://fanyi.baidu.com/") # 请求过程
'''
req=request.Request("https://fanyi.baidu.com/")
reponse=request.urlopen(req)
'''
html = reponse.read()
html = html.decode('utf-8') # decode()对网页信息进行解码
print(html)
II.获取服务器响应信息:request.urlopen()代表请求过程返回的HTTPResponse对象代表响应,其status属性返回请求HTTP后的状态,reason属性可以得到未被响应的原因:
# part 2
from urllib import request
rep=request.Request("https://fanyi.baidu.com")
reponse=request.urlopen(rep)
data=reponse.read
print('status:',reponse.status,reponse.reason)
print("************************************\n")
for k,v in reponse.getheaders():
print('%s:%s' % (k,v))
或者
# part 3
from urllib import request
# 使用Reponse 对象的geturl()方法、info()方法、getcode()方法获取相关的URL、相应信息和响应HTTP状态码
if __name__=="__main__":
req=request.Request("https://fanyi.baidu.com")
reponse=request.urlopen(req)
print('(1)URL信息:%s'%(reponse.geturl()))
print('**************************************')
print('(2)info 信息:%s'%(reponse.info()))
print('**************************************')
print('(3)getcode 信息:%s'%(reponse.getcode()))
结果:
status: 200 OK
************************************
Content-Type:text/html; charset=utf-8
Date:Wed, 16 Sep 2020 09:15:27 GMT
P3p:CP=" OTI DSP COR IVA OUR IND COM "
Server:yunjiasu
Set-Cookie:BAIDUID=AF4DE50E23AADA1FC4BB8D292DD03D4C:FG=1; expires=Thu, 16-Sep-21 09:15:27 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1
Tracecode:09277220840490071050091617
Vary:Accept-Encoding
Yjs-Id:9528c5dc86c52846-103
Connection:close
Transfer-Encoding:chunked
III.向服务器发送数据并使用User Agent 隐藏身份: 可以使用urlopen()函数中的data参数向服务器发送数据,从客户端向服务器提交数据使用post,从服务器获得数据到客户端使用get,同时get也可以提交。有些网站不喜欢被爬虫程序访问,所以会检测链接对象,所以为了让程序可以正常运行,需要隐藏自己的爬虫程序身份,通过设置User Agent来达到隐藏身份的目的,简称UA。
# part 4
from urllib import request
# 使用user Agent 隐藏身份 (两种方法)
if __name__=="__main__":
url = 'https://fanyi,baidu.com'
req = request.Request(url) # 创建Request对象
req.add_header('User-Agent','Mozilla/5.0 (Linux;Android 4.1.1; Nexus 7 Build/JRO03D)
AppleWebKit/535.19 (KHTML, like Geoko) Chrome')
response = request.urlopen(req)
html = response.read().decode('utf-8') # 读取响应信息并解码
print(html)
三、最终实现
1、演示:
设计的为自动检测语言种类翻译成中文,要想中文翻译成其他语言,只要改变字典的from和to即可。如下:
2、代码块:
# 最终实现
from tkinter import *
from urllib import request
from urllib import parse
import json
import hashlib
def translate_Word(en_str):
URL = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
'''
en_str=input('请输入要翻译的内容‘)
创建Form Data 字典,存储向服务器发送的data,具体参见百度API文档
Form Data={'from':'en','to':'zh','q':en_str,'appid':'你的appid','salt':'你的salt'}
'''
Form_Data = {'from': 'auto', 'to': 'zh', 'q': en_str, 'appid': '你的appid', 'salt': '你的salt'}
# 创建字典,翻译语言auto(不分种类,自动检测)
Key = '你的key(字符串)'
m = Form_Data['appid'] + en_str + Form_Data['salt'] + Key
m_MD5 = hashlib.md5(m.encode('utf-8')) # 摘要算法,md5算法
Form_Data['sign'] = m_MD5.hexdigest() # 生成sign签名,32位
data = parse.urlencode(Form_Data).encode('utf-8') # 使用urlencode()方法转换为标准格式
reponse = request.urlopen(URL, data) # 传递Request 对象和转换完格式的数据
html = reponse.read().decode('utf-8')
translate_result = json.loads(html) # 使用json
print(translate_result)
translate_result = translate_result['trans_result'][0]['dst'] # 找到翻译结果
print('翻译结果是:%s' % translate_result)
return translate_result
def leftClick(event):
en_str = Entry1.get() # 获取字符
print(en_str)
vText = translate_Word(en_str)
Entry2.config(Entry2, text=vText)
s.set(" ")
Entry2.insert(0, vText)
def leftClick2(event):
s.set(" ")
Entry2.delete(0, END) # 清空
if __name__ == "__main__":
root = Tk()
root.title('单词翻译器')
root.geometry('500x300')
Label(root, text='键入翻译内容:', width=19).place(x=1, y=80) # 绝对坐标(1,1)
Entry1 = Entry(root, width=50)
Entry1.place(x=110, y=80)
Label(root, text='翻译结果(中文):', width=18).place(x=1, y=120)
s = StringVar()
s.set('Hello,this is a test for translation')
Entry2 = Entry(root, width=50, textvariable=s)
Entry2.place(x=110, y=120)
Button1 = Button(root, text='翻译', width=8)
Button1.place(x=150, y=180)
Button2 = Button(root, text='清空', width=8)
Button2.place(x=270, y=180)
Button1.bind("<Button-1>", leftClick) # 事件响应
Button2.bind("<Button-1>", leftClick2)
root.mainloop()
更多内容请访问个人博客,链接:NiKoJJ‘s Blog
同时欢迎关注微信公众号,获取更多有趣内容!