web | 爬虫有道和百度翻译

web | 爬虫有道和百度翻译

最近在玩英文galgame,老是开网页搜词很不方便,就直接自己造了个工具。

需要execjs requests,后缀pyw直接开,非常丝滑。

import requests
import execjs
import json
import tkinter


def search(keyword):
	url = "https://dict.youdao.com/suggest?num=5&ver=3.0&doctype=json&cache=false&le=en&q={}"
	r = requests.get(url.format(keyword))
	data = json.loads(r.text)
	if data['result']['code'] == 200:
		ret = []
		for word in data['data']['entries']:
			ret.append(f'【{word["entry"]}】: {word["explain"]}')
		return ret

def translate(s):
	url = 'https://fanyi.baidu.com/v2transapi'
	headers = {'cookie': "BAIDUID=2D5A11B6B78ACE662B416CD6A2FF1EAC:FG=1; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1679124422; APPGUIDE_10_0_2=1; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; BIDUPSID=2D5A11B6B78ACE662B416CD6A2FF1EAC; PSTM=1679127601; H_PS_PSSID=26350; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; ZFY=55OaQBm:BUlESEj4:AHcm4I5g7PxQuLtKxWXkCcS5SEmI:C; BAIDUID_BFESS=2D5A11B6B78ACE662B416CD6A2FF1EAC:FG=1; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1679127607; ab_sr=1.0.1_NWJmMzQ3N2Q1ZjI0OGVmNGY4ZDViNzNlZDI1MWJiYjE3YzI3YmI3NWZlMzVkYWRmNjU1OGMzMjY0ZTE2OGU2MmUyNTY5MjkxNTViYzA2NWVmZDMzZDdmMDNlYjU2ZDI1ZDE0OTQwOTAxZDg0MmRmYjYzNDJiNDcyMDE0ZWEzOGVkZmY2OGRmMDEwZDAwOWJmNWMzYzkwMjI0NGZhYmU4Yw=="}
	js1= r'''
	var r = "320305.131321201"
	function n(r, o) {
		for (var t = 0; t < o.length - 2; t += 3) {
			var a = o.charAt(t + 2);
			a = a >= "a" ? a.charCodeAt(0) - 87 : Number(a), a = "+" === o.charAt(t + 1) ? r >>> a : r << a, r = "+" === o.charAt(t) ? r + a & 4294967295 : r ^ a
		}
		return r
	}
	function sign(t) {
		var o, i = t.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g);
		if (null === i) {
			var a = t.length;
			a > 30 && (t = "".concat(t.substr(0, 10)).concat(t.substr(Math.floor(a / 2) - 5, 10)).concat(t.substr(-10, 10)))
		} else {
			for (var s = t.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/), c = 0, l = s.length, u = []; c < l; c++)
				"" !== s[c] && u.push.apply(u, function(t) {
					if (Array.isArray(t))
						return e(t)
				}(o = s[c].split("")) || function(t) {
					if ("undefined" != typeof Symbol && null != t[Symbol.iterator] || null != t["@@iterator"])
						return Array.from(t)
				}(o) || function(t, n) {
					if (t) {
						if ("string" == typeof t)
							return e(t, n);
						var r = Object.prototype.toString.call(t).slice(8, -1);
						return "Object" === r && t.constructor && (r = t.constructor.name),
						"Map" === r || "Set" === r ? Array.from(t) : "Arguments" === r || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r) ? e(t, n) : void 0
					}
				}(o) || function() {
					throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")
				}()),
				c !== l - 1 && u.push(i[c]);
			var p = u.length;
			p > 30 && (t = u.slice(0, 10).join("") + u.slice(Math.floor(p / 2) - 5, Math.floor(p / 2) + 5).join("") + u.slice(-10).join(""))
		}
		for (var d = "".concat(String.fromCharCode(103)).concat(String.fromCharCode(116)).concat(String.fromCharCode(107)), h = (null !== r ? r : (r = window[d] || "") || "").split("."), f = Number(h[0]) || 0, m = Number(h[1]) || 0, g = [], y = 0, v = 0; v < t.length; v++) {
			var _ = t.charCodeAt(v);
			_ < 128 ? g[y++] = _ : (_ < 2048 ? g[y++] = _ >> 6 | 192 : (55296 == (64512 & _) && v + 1 < t.length && 56320 == (64512 & t.charCodeAt(v + 1)) ? (_ = 65536 + ((1023 & _) << 10) + (1023 & t.charCodeAt(++v)),
			g[y++] = _ >> 18 | 240,
			g[y++] = _ >> 12 & 63 | 128) : g[y++] = _ >> 12 | 224,
			g[y++] = _ >> 6 & 63 | 128),
			g[y++] = 63 & _ | 128)
		}
		for (var b = f, w = "".concat(String.fromCharCode(43)).concat(String.fromCharCode(45)).concat(String.fromCharCode(97)) + "".concat(String.fromCharCode(94)).concat(String.fromCharCode(43)).concat(String.fromCharCode(54)), k = "".concat(String.fromCharCode(43)).concat(String.fromCharCode(45)).concat(String.fromCharCode(51)) + "".concat(String.fromCharCode(94)).concat(String.fromCharCode(43)).concat(String.fromCharCode(98)) + "".concat(String.fromCharCode(43)).concat(String.fromCharCode(45)).concat(String.fromCharCode(102)), x = 0; x < g.length; x++)
			b = n(b += g[x], w);
		return b = n(b, k),
		(b ^= m) < 0 && (b = 2147483648 + (2147483647 & b)),
		"".concat((b %= 1e6).toString(), ".").concat(b ^ f)
	}
	'''
	From = 'en'
	To = 'zh'
	token = 'c2d5d0b021ef0780e861e0d170858d2a'
	q = s   # 要查询的
	sign = execjs.compile(js1).call("sign", q)
	data = {'from':From,'to':To,'query':q,'sign':sign,'token':token}
	text = requests.post(url,headers=headers,data=data).json()['trans_result']['data'][0]['dst']
	return [text]

def btn_search():
	# 获取要查的词 判断是句子还是单词
	keyword = text.get('0.0','end').strip()
	# 搜索并显示
	if ' ' in keyword:
		ret = translate(keyword)
	else:
		ret = search(keyword)
	print(ret)
	result_text.configure(state='normal')
	result_text.delete('0.0','end')
	result_text.insert('end', '\r\n'.join(ret))
	result_text.configure(state='disabled')
	
def tab_ret(s):
	btn_search()
	return 'break'

window = tkinter.Tk()
window.title("Dictionary@Mz1")
window.geometry('300x380')
window.resizable(0,0)
window.attributes('-topmost',True)

head = tkinter.Label(window, text="查英文单词/翻译", font=('Times', 15))
button = tkinter.Button(window, text="搜索", command=btn_search)
text = tkinter.Text(window, width=25, height=1, undo=True, autoseparators=False)
text.configure(font=("Times", 15))
text.bind('<Return>', tab_ret)   # 限制回车
result_text = tkinter.Text(window, width=25, height=12)
result_text.configure(state='disabled', font=("Times", 15))

head.pack()
text.pack()
button.pack()
result_text.pack()


if __name__ == '__main__':
	window.mainloop()

posted @ 2023-03-18 16:32  Mz1  阅读(32)  评论(0编辑  收藏  举报