爬虫自制翻译器 [爬虫专题(16)]

版权声明:Hi,I m Debroon【Q:23609099,青睐互动 https://blog.csdn.net/qq_41739364/article/details/88849586

完整形式:

爬取网址:http://fanyi.youdao.com/

为了编程,我决定要把英语纳入我的常用语言。在啃英文文档的时候,往往会帮您打开学习编程的一条捷径。

也许,您会觉得,现在的翻译器已经很好了。会不会英语其实,无所谓。

的确,对于别人来说,以后会不会英语也许只是一种人与人之间比较的 '品味高低'

但对于想当独一无二的编程大师的我来说,要想达成目标,只在中国的眼界多少比不上国际的大师。为了编程,我可以付出我的时间、精力,也愿意因为TA时刻保持一种对事物呈接受的本能状态。


首先我们看看TA的请求方式。 因为有输入,所以呢,TA是一个 Post 请求。

好吧,我们还是打开 General ( 鼠标右键 -> 检查 -> Network -> Headers -> General ) 瞧瞧:

 Method (请求方式) : Post

哦,对了。URL也需要的。 

第一个 Request URL 里面到链接里有我们想要的翻译结果。所以,访问这个网页就好哩。

那么,为什么是这个 XHR 文件里的链接,而不是有道网页的主链接呢 ?

           因为XHR:采用 Ajax技术,更新网页内容,但重新加载整个网页或者跳转到新网页,这样省流量又也省时间。

           而采用 XHR 是因为,我们的数据是 json 格式存储的,如图:

        

           json是一种跨平台组织数据的格式,和Python中的列表/字典像似,不过TA并不是列表/字典(json有俩种方法转换)。TA和html一样,常用来做网络数据传输。XHR能传输很多种数据,json是XHR中被传输的一种数据格式。

           所以,我们只需要这个网址即可。

第三个 是状态码,一般而言 状态码 在 200到299都是正常访问的。

第四个 是服务器的IP地址(220.181.76.83):端口(80)

第五个 是记录请求来源的信息


接着,我们观看输入的内容,在 From data ( 鼠标右键 -> 检查 -> Network -> Headers -> From data ) 看到上传的 内容


暂停一下,着手写代码吧~


import requests, json

url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

content = input('请输入您需要翻译的文字或网址:>  ')
data = {
    'i': content,
    'from': 'AUTO',
    'to': 'AUTO',
    'smartresult': 'dict',
    'client': 'fanyideskweb',
    'doctype': 'json',
    'version': '2.1',
    'keyfrom': 'fanyi.web',
    'action': 'FY_BY_REALTIME',
    'typoResult': 'false'
}
# 把 From data copy下来,以字典形式保留
res = requests.get(url, data = data)
j_res = res.json()
# 使用json()方法,将response对象,转为列表/字典 或者 使用 j_res = json.loads(res.text)

Then, 取出翻译结果即可:因为我们把 json 转为了 列表/字典,那么这个网页您现在可以看成列表/字典了。

           print(j_res):

提问内容:

quiz = j_res['translateResult'][0][0]['src']

翻译结果:

answer['translateResult'][0][0]['tgt']

完整代码如下:

import requests, json

url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

content = input('请输入您需要翻译的文字或网址:>  ')
data = {
    'i': content,
    'from': 'AUTO',
    'to': 'AUTO',
    'smartresult': 'dict',
    'client': 'fanyideskweb',
    'doctype': 'json',
    'version': '2.1',
    'keyfrom': 'fanyi.web',
    'action': 'FY_BY_REALTIME',
    'typoResult': 'false'
}
# 把 From data copy下来,以字典形式保留
res = requests.get(url, params = data)
j_res = res.json()
# 使用json()方法,将response对象,转为列表/字典 或者 使用 j_res = json.loads(res.text)

quiz = j_res['translateResult'][0][0]['src']
answer = j_res['translateResult'][0][0]['tgt']
print(quiz, answer)

考虑我们会经常用到,需要快速打开的。这里,我提供一种Mac用 finder(option+command+space) 快速打开的方法。

    0. 在第一行加一句 >> #!/usr/bin/env python,完整代码:

#!/usr/bin/env python
import requests, json

content = input(":>  ")

url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

data = {
    'i': content,
    'from': 'AUTO',
    'to': 'AUTO',
    'smartresult': 'dict',
    'client': 'fanyideskweb',
    'doctype': 'json',
    'version': '2.1',
    'keyfrom': 'fanyi.web',
    'action': 'FY_BY_REALTIME',
    'typoResult': 'false'
}

r = requests.post(url,data)
answer=json.loads(r.text)

print (answer['translateResult'][0][0]['src'])
print (answer['translateResult'][0][0]['tgt'])
  1. 把当前文件 aa.py(假名)文件改为 aa.command文件(可以用pycharm改 或command+f 找到文件改)
  2. 考虑到编码,需要把所有中文注释全部换掉

         Python 3 版本中,字符串是以 Unicode 编码的,也就是说,Python 的字符串支持多 语言,比如中文。当你的源代码中包含中文的时候,在保存源代码时,就需要务必指定保 存为 UTF-8 编码。当 Python 解释器读取源代码时,为了让它按 UTF-8 编码读取,我们通 常在文件开头写上这行:或者使用

         # -*- coding: utf-8 -*-

         注释是为了告诉 Python 解释器,按照 UTF-8 编码读取源代码,否则,你在源代码中写的 中文输出可能会有乱码。但是申明了 UTF-8 编码并不意味着你的.py 文件就是 UTF-8 编码 的,必须并且要确保文本编辑器正在使用 UTF-8 without BOM 编码。

     3. 打开终端,进去到 aa.command 文件的目录

     4. 进去后,在终端输入:> chmod +x aa.command

     5.  同时按住 3 个键:>  option+command+space,搜索 aa.command 双击运行即可

     

 输入的话,需要带一个 引号 ,不要问我,我也不知道为什么会这样 。所以,输入如,'xxx'

                    OK啦 KO啦! ! !


         可是,这样还是挺不方便的。因为我翻译的时候,要做无用功啊,比如,我copy了一段话,还需要 command+V 输入进去,这里我觉得完全可以改进改进。copy在剪切板时,让程序自动输入进去即可~ 实现TA也简单,引入一个模块即可。

import requests, json, pyperclip
# pyperclip获取数据来源

content = pyperclip.paste()
# 将剪切板里的内容给yuanwen

url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

data = {
    'i': content,
    'from': 'AUTO',
    'to': 'AUTO',
    'smartresult': 'dict',
    'client': 'fanyideskweb',
    'doctype': 'json',
    'version': '2.1',
    'keyfrom': 'fanyi.web',
    'action': 'FY_BY_REALTIME',
    'typoResult': 'false'
}

r = requests.post(url,data)
answer=json.loads(r.text)
print ('翻译的提问是:'+answer['translateResult'][0][0]['src'])
print ('翻译的结果是:'+answer['translateResult'][0][0]['tgt'])

pyperclip.copy(answer['translateResult'][0][0]['tgt'])
print('翻译结果已复制至剪切板')

可这样的翻译器,好没逼格啊。要一个带界面的,可以用TK、PyQt5、wxPython实现,这里给出TK实现的:

import requests
import json
from tkinter import Tk, Button, Entry, Label, Text, END


class YouDaoFanyi(object):
    def __init__(self):
        pass
    def crawl(self,word):
        url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
        #使用post需要一个链接
        data={'i': word,
              'from': 'AUTO',
              'to': 'AUTO',
              'smartresult': 'dict',
              'client': 'fanyideskweb',
              'doctype': 'json',
              'version': '2.1',
              'keyfrom': 'fanyi.web',
              'action': 'FY_BY_REALTIME',
              'typoResult': 'false'}
        #将需要post的内容,以字典的形式记录在data内。
        r = requests.post(url, params = data)
        #post需要输入两个参数,一个是刚才的链接,一个是data,返回的是一个Response对象
        answer=json.loads(r.text)
        #你可以自己尝试print一下r.text的内容,然后再阅读下面的代码。
        result = answer['translateResult'][0][0]['tgt']
        return result



class Application(object):
    def __init__(self):
        self.window = Tk()
        self.fanyi = YouDaoFanyi()




        self.window.title(u'自制翻译器')
        #设置窗口大小和位置
        self.window.geometry('310x370+500+300')
        self.window.minsize(310,370)
        self.window.maxsize(310,370)
        #创建一个文本框
        #self.entry = Entry(self.window)
        #self.entry.place(x=10,y=10,width=200,height=25)
        #self.entry.bind("<Key-Return>",self.submit1)
        self.result_text1 = Text(self.window,background = 'azure')
        # 喜欢什么背景色就在这里面找哦,但是有色差,得多试试:http://www.science.smith.edu/dftwiki/index.php/Color_Charts_for_TKinter
        self.result_text1.place(x = 10,y = 5,width = 285,height = 155)
        self.result_text1.bind("<Key-Return>",self.submit1)


        #创建一个按钮
        #为按钮添加事件
        self.submit_btn = Button(self.window,text=u'翻译',command=self.submit)
        self.submit_btn.place(x=205,y=165,width=35,height=25)
        self.submit_btn2 = Button(self.window,text=u'清空',command = self.clean)
        self.submit_btn2.place(x=250,y=165,width=35,height=25)


        #翻译结果标题
        self.title_label = Label(self.window,text=u'翻译结果:')
        self.title_label.place(x=10,y=165)
        #翻译结果


        self.result_text = Text(self.window,background = 'light cyan')
        self.result_text.place(x = 10,y = 190,width = 285,height = 165)
        #回车翻译
    def submit1(self,event):
        #从输入框获取用户输入的值
        content = self.result_text1.get(0.0,END).strip().replace("\n"," ")
        #把这个值传送给服务器进行翻译


        result = self.fanyi.crawl(content)
        #将结果显示在窗口中的文本框中


        self.result_text.delete(0.0,END)
        self.result_text.insert(END,result)

        #print(content)

    def submit(self):
        #从输入框获取用户输入的值
        content = self.result_text1.get(0.0,END).strip().replace("\n"," ")
        #把这个值传送给服务器进行翻译


        result = self.fanyi.crawl(content)
        #将结果显示在窗口中的文本框中


        self.result_text.delete(0.0,END)
        self.result_text.insert(END,result)
        print(content)
    #清空文本域中的内容
    def clean(self):
        self.result_text1.delete(0.0,END)
        self.result_text.delete(0.0,END)


    def run(self):
        self.window.mainloop()




if __name__=="__main__":
    app = Application()
    app.run()

猜你喜欢

转载自blog.csdn.net/qq_41739364/article/details/88849586
今日推荐