原创

基于python语言爬取有道翻译实现的翻译小软件


基于python语言爬取有道翻译实现的翻译小软件

使用tkinter模块实现界面
使用requests模块实现翻译内容的爬取功能
from tkinter import *
from tkinter import messagebox
import requests


# ========翻译功能实现========== #
def translation():
    content = entry.get()
    content = content.strip()
    if content == '':
        messagebox.showinfo('提示', message='请输入要翻译的内容')
    else:
        # 设置head是为了防止网站检测封锁ip
        head = {}
        head['User-Agent'] = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Mobile Safari/537.36'
        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'] = '15804708082714'
        # data['sign'] = '41c02d0f45b83abcbd3ef081478a291a'
        # data['ts'] = '1580470808271'
        # data['bv'] = '8c1d961492d2126df817a1dafe4e9e56'

        data['doctype'] = 'json'
        data['version'] = '2.1'
        data['keyfrom'] = 'fanyi.web'
        data['action'] = 'FY_BY_CLICKBUTTION'

        result = requests.post(url, data, head)
        result = result.json()
        result = result['translateResult'][0][0]['tgt']
        res.set(result)


# ========界面实现========== #
# 创建窗口
window = Tk()
# 设置窗口大小
window.geometry('500x100+500+250')
# 设置标题
window.title('基于python的翻译小项目')

# 控件(提示文字)
label = Label(window, text='请输入要翻译的内容:', font=('隶书', 18), fg='orange')
label.grid(row=0, column=0)
# 输入框
entry = Entry(window, font=('隶书', 18))
entry.grid(row=0, column=1)

# 控件(提示文字)
label1 = Label(window, text='翻译结果:', font=('隶书', 18), fg='orange')
label1.grid(row=1, column=0)
# 输入框(这里设置一个随时变化的变量,显示输出结果)
res = StringVar()
entry1 = Entry(window, font=('隶书', 18), textvariable=res)
entry1.grid(row=1, column=1)

# 按钮
button = Button(window, text='翻译', width=10, command=translation)
button.grid(row=2, column=0, sticky=W)
button = Button(window, text='退出', width=10, command=window.quit)
button.grid(row=2, column=1, sticky=W)

# 显示窗口
window.mainloop()

360版本

import requests
import json
from tkinter import Tk, Text, Button, Entry, NSEW, StringVar, messagebox, END


def translation():
    query = entry.get().strip()
    if query == '':
        messagebox.showinfo('提示', message='请输入要翻译的内容')
    else:
        if check_contain_chinese(query):
            eng = 0
        else:
            eng = 1
        url = 'http://fanyi.so.com/index/search'
        headers = {
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400',
            'Accept': 'application/json, text/plain, */*',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Connection': 'keep-alive',
            'Content-Length': '0',
            'Cookie': '',
            'Host': 'fanyi.so.com',
            'Origin': 'http://fanyi.so.com',
            'pro': 'fanyi',
            'Referer': 'http://fanyi.so.com/'
        }

        data = {}
        data['eng'] = eng  # 中->英:0  英->中:1
        data['validate'] = ''
        data['ignore_trans'] = 0
        data['query'] = query

        response = requests.post(url, headers=headers, data=data)
        response = json.loads(response.text)
        if eng == 0:
            text.delete(1.0, END)
            text.insert(1.0, response['data']['fanyi'])
        else:
            try:
                if response['data']['explain']['translation'] != None:
                    text.delete(1.0, END)
                    for i in response['data']['explain']['translation']:
                        text.insert(1.0, i + '\n')

            except:
                text.delete(1.0, END)
                text.insert(1.0, response['data']['fanyi'])


def check_contain_chinese(check_str):
    for ch in check_str:
        if u'\u4e00' <= ch <= u'\u9fff':
            return True
    return False


if __name__ == '__main__':
    root = Tk()
    win_width = root.winfo_screenwidth()
    win_height = root.winfo_screenheight()
    root.geometry('385x220+' + str(int(win_width / 2 - 192)) + '+' + str(int(win_height / 2 - 110)))
    root.minsize(385, 220)
    root.maxsize(385, 220)
    root.title('360翻译小软件-敲出一片天')

    query = StringVar()
    query.set('请输入需要翻译的内容')
    entry = Entry(root, width=20, font=('隶书', 18), textvariable=query)

    entry.grid(row=0, column=0, pady=10, padx=10, sticky=NSEW)
    button = Button(root, text='翻译', command=translation)
    button.grid(row=0, column=1, pady=10, padx=10, sticky=NSEW)
    result = StringVar()
    text = Text(root, width=30, height=6, font=('隶书', 18))
    text.grid(row=1, column=0, columnspan=2, pady=10, padx=10, sticky=NSEW)

    root.mainloop()

python
爬虫
  • 作者:曾强(联系作者)
  • 发表时间:2020-05-03 22:55
  • 版权声明:自由转载-非商用-非衍生-保持署名
  • 转载声明:转载时请注明出处:www.zengqiang.club
  • 注:如果文章有错误,望请评论指出,谢谢;如果看了文章还有不明白的地方,欢迎进群与我交流。
  • 评论