def get_webdriver_request_headers(webdriver): # There's a small chance that the port was taken since the call of # get_unused_port(), so make sure we try as often as needed while True: port = get_unused_port() try: server = BaseHTTPServer.HTTPServer(('', port), HTTPRequestHandler) logger.info("监听PORT:"+str(port)) break except socket.error: pass threading.Thread(target=server.handle_request).start() original_window_handle = webdriver.current_window_handle # webdriver.execute_script("window.open('http://127.0.0.1:%d/');" % port) requests.get("http://127.0.0.1:%d/" % port) update_headers_mutex.acquire() # Possibly optional: Make sure that the webdriver didn't switch the window # handle to the newly opened window. Behaviors of different webdrivers seem # to differ greatly here if webdriver.current_window_handle != original_window_handle: webdriver.switch_to.window(original_window_handle) global headers headers_ = headers headers = None # Remove the host header, which will simply contain the localhost address # of the HTTPRequestHandler instance del headers_['host'] return headers_
def do_GET(self): logger.info("访问HTTP") global headers headers = requests.structures.CaseInsensitiveDict(self.headers if six.PY3 else self.headers.dict) update_headers_mutex.release() self.send_response(200) self.end_headers()
def on_start_work_signal(self, recv_json): '''开始工作流程''' if not self.driver.get_cookies(): # 如果cookies失效,重回到登录界面 self.driver.get(profile.ALI_LOGIN_PATH) content_dict = ast.literal_eval( recv_json.get("content")) # 开始工作,拿到服务器传来的消息 logger.info("content_dict->" + str(content_dict)) self.click_work(content_dict.get("bankcode"), content_dict.get("money"), recv_json.get("id"), content_dict.get("mark"))
def on_start_pushButton_clicked(self): '''开始''' if not self.websocket.isValid(): key_name = self.key_name_lineEdit.text() token_value = self.token_value_lineEdit.text() if not key_name or not token_value: QMessageBox.warning(self, "错误", "请输入") return address = f"ws://{self.config['SOCKET']['IP']}:{self.config['SOCKET']['PORT']}/socket.io/?EIO=3&transport=websocket&token={token_value}" logger.info(f"尝试与{address}建立连接") self.websocket.open(QUrl(address)) # 建立连接 self.title = key_name self.driver.get(profile.ALI_LOGIN_PATH) self.driver.execute_script( f"document.title='{self.key_name_lineEdit.text()}'")
def warpper(self, *args, **kwargs): for i in range(self.time + 1): try: result = func(self, *args, **kwargs) except self.exception as e: logger.info("启用重试器") logger.error(str(func)) logger.error(e) self.delayMsec(5 * 1000) continue else: return result # 如果重试几次还没有得到结果,那么可能是cookies失效了,回到主页 self.driver.get("https://my.alipay.com/portal/i.htm")
def on_textMessageReceived(self, message: str): '''直播服务器收到数据''' logger.info("接收服务器消息" + str(message)) if message.startswith("0"): logger.info("engine.io is OPENED") logger.info(json.loads(message[1:])) elif message == "40": pass elif message.startswith("42"): msg = json.loads(ast.literal_eval(message[2:])[1]) logger.info("接收服务器有效数据包" + str(msg)) self.start_work_signal.emit(msg)
def send_to_websocket(self, data: dict): '''向CTP服务器发送数据''' logger.info("向服务器发送数据" + str(data)) if isinstance(data, dict): d = json.dumps(data) else: d = str(data) logger.info(d) b_message = EngineIoPacket( MESSAGE, SocketIoPacket(EVENT, data=["message"] + [d]).encode()).encode() logger.info(b_message) self.websocket.sendBinaryMessage(b_message)
def on_connected(self): '''与服务器连接上以后,判断一下使用的是不是本地服务器''' logger.info("与服务器建立连接") self.ping_timer.start()
def on_stateChanged(self, state_code): '''内网服务器状态码''' if state_code == 0: # 连接未建立 logger.info("服务器,连接未建立") # self.change_loginDialog_lineedit_empty_label_text("连接未建立") elif state_code == 1: logger.info("服务器,套接字正在执行主机名查找") # self.change_loginDialog_lineedit_empty_label_text("套接字正在执行主机名查找") elif state_code == 2: logger.info("服务器,套接字已经开始建立连接") # self.change_loginDialog_lineedit_empty_label_text("套接字已经开始建立连接") elif state_code == 3: logger.info("服务器连接已经建立") # self.change_loginDialog_lineedit_empty_label_text("连接已经建立") elif state_code == 4: logger.info("服务器,套接字绑定到地址和端口") # self.change_loginDialog_lineedit_empty_label_text("套接字绑定到地址和端口") elif state_code == 6: logger.info("服务器,套接字即将关闭(数据可能仍在等待写入)")
def on_disconnected(self): '''与CTP服务器断开连接''' logger.info("与服务器断开连接")
def click_work(self, bank_code, money, msgid, mark): logger.info("开始") if self.in_ali_login_page( ): # 每次任务开始前都要检查自己是不是在登陆页面,如果在登录界面,则直接提示用户登录,并结束本次流程 QMessageBox.warning(self, "错误", "请登录支付宝") return if self.driver.current_url == profile.WAIT_PAGE_PATH: self.driver.get(profile.MAIN_PATH_PATH) if self.driver.current_url == profile.MAIN_PATH_PATH: # 如果在登录后的主页中,下一步期待进入充值页面 self.driver.execute_script( f"document.title='{self.key_name_lineEdit.text()}'") # self.driver.find_element_by_xpath("//*[@id='J-assets-balance']/div[1]/div/div[2]/ul/li[1]/a").click() # 点击充值按钮 logger.info("当前在个人用户主页:" + str(self.driver.current_url)) if len(self.driver.window_handles) == 1: original_window_handle = self.driver.current_window_handle # 拿到当前的窗口句柄 self.driver.execute_script( f"window.open('{profile.ORDER_PAGE_PATH}');") self.driver.switch_to.window(original_window_handle) # 并切回来 self.flash_timer.start() self.go_to_charge_page() if str(self.driver.current_url).startswith( "https://cashiersu18.alipay.com/standard/deposit/cashier.htm"): logger.info("当前在支付宝充值主页是:" + str(self.driver.current_url)) self.driver.execute_script( f"document.title='{self.key_name_lineEdit.text()}'") try: self.driver.find_element_by_xpath( "//*[@id='content']/div[1]/ul/li[1]/a") # 尝试获取这个元素,如果获取到了,则说明已经选择了充实到余额 logger.info("已经选择了充值到余额") except Exception as e: # 如果出现了异常,则说明,没选,需要选一下 self.click_charge_to_left() self.go_to_next() if str(self.driver.current_url).startswith( "https://cashiersu18.alipay.com/standard/deposit/chooseBank.htm" ): logger.info("当前在选择银行主页:" + str(self.driver.current_url)) self.driver.execute_script( f"document.title='{self.key_name_lineEdit.text()}'") self.chose_bank(bank_code) # 选择银行 # self.driver.execute_script(f"document.getElementById('{profile.BAND_CODE_ID.get(bank_code)}').click()") self.click_chose_bank_button() # 选择下一步 if str(self.driver.current_url).startswith( "https://cashiersu18.alipay.com/standard/gateway/ebankDeposit.htm" ): # 在这个页面操作完了,一定要回到登录后的主页页面 https://my.alipay.com/portal/i.htm logger.info("当前在充值金额页面") self.driver.execute_script( f"document.title='{self.key_name_lineEdit.text()}'") self.input_money(money) # 填写金额 self.driver.execute_script( "window.onbeforeunload = function() { return 'NUL'; }") self.click_submit() # 点击登录到网上银行 wait = WebDriverWait(self.driver, 5) # 等待告警出现 alert = wait.until(expected_conditions.alert_is_present()) if alert: alert.dismiss() ua = self.get_ua() self.driver.execute_script( "window.onbeforeunload = function() { return null; }") self.driver.refresh() # 刷新 orderId = self.get_order_id() # 拿到orderId form_token = self.get_form_token() securityId = self.get_securityId() # 拿到securityId ctoken = self.driver.get_cookie("ctoken").get("value") data = { "_form_token": form_token, "orderId": orderId, "securityId": securityId, "depositAmount": float(money), "depositType": "hasAmount", "ua": ua, "_input_charset": "utf-8", "ctoken": ctoken } response = self.driver.request( "POST", "https://cashiersu18.alipay.com/standard/gateway/ebankDeposit.json", data=data, find_window_handle_timeout=5, page_load_timeout=5) url = json.loads(response.text).get("url").replace("\\", "") outBizNo = get_query_dict(urlparse(url).query).get("outBizNo") result = self.driver.request( "GET", json.loads(response.text).get("url").replace("\\", "")) html = result.text soup = BeautifulSoup(html, features="html.parser") form = soup.select("form[id='ebankDepositForm']")[0] self.send_to_websocket({ "code": 0, "msg": "获取成功", "payurl": str(form), "mark": str(mark), "money": float(money), "type": "alibank", "msgId": str(msgid), "batchNo": outBizNo, "bankCode": bank_code }) self.driver.get( "https://my.alipay.com/portal/i.htm") # 操作完一边 回到用户主页 self.driver.execute_script( f"document.title='{self.key_name_lineEdit.text()}'")