前言
简单的JS逆向爬虫,本文例子有道翻译,相信网上有很多教程就不想细说的,用PyQt5制作简单的界面,最后用pyinstaller打包,自定义图标
首先开看一下成果图:输入一段英文:Over at the brand new Aquatics Centre, Britain’s star diver Tom Daley is going to perform an official launch dive into the Olympic pool.点击翻译按钮,提示框给出翻译结果。
步骤
1.引入库
需要使用的库:
import requests
import time
import random
from loguru import logger
import sys
import easygui as g
import io
import hashlib
import threading
from PyQt5.QtGui import QIcon,QFont
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtWidgets import *
2代码示例
1:创建get_md5.py,构造一个函数,MD5加密:
import hashlib
def Md5(arg):
md5 = hashlib.md5()
md5.update(arg.encode('utf-8'))
result = md5.hexdigest()
return result
if __name__ == '__main__':
v = Md5(arg="5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36")
print(type(v))
2:创建app01.py,破解有道翻译接口,具体思路向数据库获取动态ip,然后范文有道翻译网站得到cookies,然后再去访问http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule为了防止反爬,据测试好像不需要,可以把get_ip,get_cookie去掉,最后封装一下
import requests
import time
import random
from loguru import logger
from dbutil import MySQL
from get_md5 import Md5
url1 = "http://fanyi.youdao.com/"
headers1 = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36"
}
url2 = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
class YDFanYi(object):
def __init__(self,test):
self.test = test
def get_ip(self):
try:
db = MySQL.conn_mysql()
random_num = int(random.randint(1, 40))
result = MySQL.sel_table("select * from proxies limit %s,1" % random_num, db)
msg = {}
proxy = {}
for i in result:
msg['ip'] = i[0]
proxy['http'] = i[2]
proxy['https'] = i[3]
msg['proxy'] = proxy
if msg == {}:
return self.get_ip()
return msg
except:
return self.get_ip()
def get_cookie(self):
msg = self.get_ip()
proxy = msg["proxy"]
try:
res = requests.get(url=url1,headers=headers1,proxies=proxy,timeout=10)
temp_cookie = res.cookies
return temp_cookie
except:
return self.get_cookie()
def get_url(self):
msg = self.get_ip()
proxy = msg["proxy"]
temp_cookies = self.get_cookie()
tmp_cookies = dict(temp_cookies)
i = self.test
lts = int(time.time() * 1000)
a = int(time.time() * 1000)
b = random.randint(0, 9)
salt = str(a) + str(b)
bv = Md5(
"5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36")
sign = Md5("fanyideskweb" + i + salt + "]BjuETDhU)zqSxf-=B#7m")
data = {
"i": i,
"from": "AUTO",
"to": "AUTO",
"smartresult": "dict",
"client": "fanyideskweb",
"salt": salt,
"sign": sign,
"lts": lts,
"bv": bv,
"doctype": "json",
"version": "2.1",
"keyfrom": "fanyi.web",
"action": "FY_BY_CLICKBUTTION",
}
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en,zh;q=0.9,zh-TW;q=0.8,en-US;q=0.7",
"Connection": "keep-alive",
"Content-Length": "243",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Cookie": "OUTFOX_SEARCH_USER_ID=%s; JSESSIONID=%s;"%(tmp_cookies["OUTFOX_SEARCH_USER_ID"],tmp_cookies["JSESSIONID"]),
"Host": "fanyi.youdao.com",
"Origin": "http://fanyi.youdao.com",
"Referer": "http://fanyi.youdao.com/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36",
"X-Requested-With": "XMLHttpRequest"
}
i = 0
while True:
i = i + 1
if i <= 10:
try:
response = requests.post(url=url2, data=data, headers=headers,proxies=proxy,timeout=10).json()
for group1 in response["translateResult"]:
for group2 in group1:
result = group2["tgt"]
return result
except:
return self.get_ip()
else:
self.get_url()
def run(self):
res = self.get_url()
return res
if __name__ == '__main__':
i = 0
while True:
i = 1 + i
results = input("请输入单词或者一句英文:")
obj = YDFanYi(test=results)
print(obj.run())
3:创建fy_app.py,diy你的界面:
import sys
from PyQt5.QtWidgets import QApplication,QWidget,QPushButton,QToolTip,QMessageBox,QDesktopWidget
from PyQt5.QtGui import QIcon,QFont
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtWidgets import *
from app01 import YDFanYi
import easygui as g
import io
import threading
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')
class Example(QWidget):
def __init__(self):
super().__init__()
self.inintUI()
def inintUI(self):
# 这种静态的方法设置一个用于显示工具提示的字体。我们使用10px滑体字体。
QToolTip.setFont(QFont('SansSerif',10))
btn = QPushButton('英译汉', self)
btn.setToolTip('来源于有道翻译接口')
btn.resize(btn.sizeHint())
btn.move(50, 50)
# 退出按钮
qbtn = QPushButton('关闭窗口',self)
qbtn.clicked.connect(QCoreApplication.instance().quit)
qbtn.resize(qbtn.sizeHint())
qbtn.move(700,700)
# 输入框
self.url_label = QLabel("请输入单词或者一句英文:",self)
self.url_label.move(30, 150)
self.url_label.resize(150, 30)
self.url_input = QLineEdit(self)
self.url_input.move(200, 150)
self.url_input.resize(500, 30)
self.url_input.returnPressed.connect(self.create_thread)
# 翻译按钮,调取数据增加函数等
self.download_btn = QPushButton('翻译', self)
self.download_btn.move(350, 250)
self.download_btn.resize(100, 40)
self.download_btn.clicked.connect(self.create_thread)
# 标题和标图
self.setGeometry(250,150,800,800)
self.setWindowTitle('英文翻译小工具')
self.setWindowIcon(QIcon('1.jpg'))
self.show()
# 退出提示窗口
def closeEvent(self, event):
reply = QMessageBox.question(self,'英文翻译小工具提示',
'你真的要退出吗',QMessageBox.Yes | QMessageBox.No,QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
# 窗口显示屏幕中央
def Center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().Center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def create_thread(self):
self.client_th1 = threading.Thread(target=self.run_FY)
# 设置线程为守护线程,防止退出主线程时,子线程仍在运行
self.client_th1.setDaemon(True)
# 新线程启动
self.client_th1.start()
self.client_th1.join()
def run_FY(self):
try:
url_item = self.url_input.text()
if url_item != "":
obj = YDFanYi(test=url_item)
obj.run()
res = obj.run()#翻译的结果
g.msgbox(res,"翻译成功")
else:
g.msgbox("请输入英文",'翻译失败')
except:
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
4:最后打包,准备好你想要的图标是ico格式,网上有很多免费转格式的,在终端打入代码:
C:\Users\root\Desktop\有道翻译>pyi-makespec fy_app.py
生成spec文件,把你的想要的图片路径写在这里:
5:最后在终端写一段代码,安装没报错就应该没问题了
C:\Users\root\Desktop\有道翻译>pyinstaller -F fy_app.py
总结
小程序可能会有漏洞,界面设计也不怎么好看,还需要优化,有兴趣一起交流学习!