def go_login(self): """ 登陆 :param user: 账户名 :param passwd: 密码 :return: """ if self.is_auto_code and self.auto_code_type == 1: balance = DamatuApi( _get_yaml()["auto_code_account"]["user"], _get_yaml()["auto_code_account"]["pwd"]).getBalance() if int(balance) < 40: raise balanceException(u'余额不足,当前余额为: {}'.format(balance)) user, passwd = _get_yaml()["set"]["12306account"][0][ "user"], _get_yaml()["set"]["12306account"][1]["pwd"] self.user, self.passwd = user, passwd if not user or not passwd: raise UserPasswordException(u"温馨提示: 用户名或者密码为空,请仔细检查") # login_num = 0 while True: if not getPassCodeNewOrderAndLogin(session=self.session, imgType="login"): continue else: # self.check_code() break pub.subscribe(self.check_code, 'rand_code')
def sendPushBear(msg): """ pushBear微信通知 :param str: 通知内容 content :return: """ conf = _get_yaml() user = _get_yaml()["set"]["12306account"][0]["user"] if conf["pushbear_conf"][ "is_pushbear"] and conf["pushbear_conf"]["send_key"].strip() != "": try: sendPushBearUrls = urls.get("Pushbear") data = { "sendkey": conf["pushbear_conf"]["send_key"].strip(), "text": user + "购票成功通知", "desp": msg } httpClint = HTTPClient(0) sendPushBeaRsp = httpClint.send(sendPushBearUrls, data=data) if sendPushBeaRsp.get("code") is 0: print(u"已下发 pushbear 微信通知, 请查收") else: print(sendPushBeaRsp) except Exception as e: print(u"pushbear 配置有误 {}".format(e)) else: pass
def go_login(self): """ 登陆 :param user: 账户名 :param passwd: 密码 :return: """ if self.is_auto_code and self.auto_code_type == 1: balance = DamatuApi(_get_yaml()["auto_code_account"]["user"], _get_yaml()["auto_code_account"]["pwd"]).getBalance() if int(balance) < 40: raise balanceException(u'余额不足,当前余额为: {}'.format(balance)) user, passwd = _get_yaml()["set"]["12306account"][0]["user"], _get_yaml()["set"]["12306account"][1]["pwd"] if not user or not passwd: raise UserPasswordException(u"温馨提示: 用户名或者密码为空,请仔细检查") login_num = 0 while True: result = getPassCodeNewOrderAndLogin(session=self.session, imgType="login") if not result: continue self.randCode = getRandCode(self.is_auto_code, self.auto_code_type, result) login_num += 1 self.auth() if self.codeCheck(): uamtk = self.baseLogin(user, passwd) if uamtk: self.getUserName(uamtk) break # if __name__ == "__main__": # # main() # # logout()
def go_login(self): """ 登陆 :param user: 账户名 :param passwd: 密码 :return: """ if self.is_aotu_code and self.aotu_code_type == 1: balance = DamatuApi(_get_yaml()["damatu"]["uesr"], _get_yaml()["damatu"]["pwd"]).getBalance() if int(balance) < 40: raise balanceException('余额不足,当前余额为: {}'.format(balance)) user, passwd = _get_yaml()["set"]["12306count"][0]["uesr"], _get_yaml()["set"]["12306count"][1]["pwd"] if not user or not passwd: raise UserPasswordException("温馨提示: 用户名或者密码为空,请仔细检查") login_num = 0 while True: self.cookietp() self.httpClint.set_cookies(_jc_save_wfdc_flag="dc", _jc_save_fromStation="%u4E0A%u6D77%u8679%u6865%2CAOH", _jc_save_toStation="%u5170%u5DDE%u897F%2CLAJ", _jc_save_fromDate="2018-02-14", _jc_save_toDate="2018-01-16", RAIL_DEVICEID="EN_3_EGSe2GWGHXJeCkFQ52kHvNCrNlkz9n1GOqqQ1wR0i98WsD8Gj-a3YHZ-XYKeESWgCiJyyucgSwkFOzVHhHqfpidLPcm2vK9n83uzOPuShO3Pl4lCydAtQu4BdFqz-RVmiduNFixrcrN_Ny43135JiEtqLaI") self.randCode = self.readImg(self.urlConf["getCodeImg"]["req_url"]) login_num += 1 self.auth() if self.codeCheck(): uamtk = self.baseLogin(user, passwd) if uamtk: self.getUserName(uamtk) break
def go_login(self): """ 登陆 :param user: 账户名 :param passwd: 密码 :return: """ if self.is_aotu_code and self.aotu_code_type == 1: balance = DamatuApi(_get_yaml()["damatu"]["uesr"], _get_yaml()["damatu"]["pwd"]).getBalance() if int(balance) < 40: raise balanceException(u'余额不足,当前余额为: {}'.format(balance)) user, passwd = _get_yaml()["set"]["12306count"][0]["uesr"], _get_yaml( )["set"]["12306count"][1]["pwd"] if not user or not passwd: raise UserPasswordException(u"温馨提示: 用户名或者密码为空,请仔细检查") login_num = 0 while True: self.cookietp() self.urlConf["getCodeImg"]["req_url"] = self.urlConf["getCodeImg"][ "req_url"].format(random.random()) self.readImg(self.urlConf["getCodeImg"]) self.randCode = self.getRandCode() login_num += 1 self.auth() if self.codeCheck(): uamtk = self.baseLogin(user, passwd) if uamtk: self.getUserName(uamtk) break
def go_login(self): """ 登陆 :param user: 账户名 :param passwd: 密码 :return: """ if self.is_auto_code and self.auto_code_type == 1: balance = DamatuApi( _get_yaml()["auto_code_account"]["user"], _get_yaml()["auto_code_account"]["pwd"]).getBalance() if int(balance) < 40: raise balanceException(u'余额不足,当前余额为: {}'.format(balance)) user, passwd = _get_yaml()["set"]["12306account"][0][ "user"], _get_yaml()["set"]["12306account"][1]["pwd"] if not user or not passwd: raise UserPasswordException(u"温馨提示: 用户名或者密码为空,请仔细检查") login_num = 0 while True: getPassCodeNewOrderAndLogin(session=self.session, imgType="login") self.randCode = getRandCode(self.is_auto_code, self.auto_code_type) login_num += 1 self.auth() if self.codeCheck(): uamtk = self.baseLogin(user, passwd) if uamtk: self.getUserName(uamtk) break
def getRandCode(self): """ 识别验证码 :return: 坐标 """ try: if self.is_aotu_code: if self.aotu_code_type == 1: return DamatuApi(_get_yaml()["damatu"]["uesr"], _get_yaml()["damatu"]["pwd"], "./tkcode").main() elif self.aotu_code_type == 2: rc = RClient(_get_yaml()["damatu"]["uesr"], _get_yaml()["damatu"]["pwd"]) im = open('./tkcode', 'rb').read() Result = rc.rk_create(im, 6113) if "Result" in Result: return self.codexy(Ofset=",".join(list(Result["Result"])), is_raw_input=False) else: if "Error" in Result and Result["Error"]: print Result["Error"] return "" else: img = Image.open('./tkcode') img.show() return self.codexy() except: pass
def sendGetQueueCountAsync(self): """ 请求排队接口 :return: """ urls = self.session.urls["getQueueCountAsync"] data = self.data_par() getQueueCountAsyncResult = self.session.httpClint.send(urls, data) if getQueueCountAsyncResult.get("status", False) and getQueueCountAsyncResult.get("data", False): if "status" in getQueueCountAsyncResult and getQueueCountAsyncResult["status"] is True: if "countT" in getQueueCountAsyncResult["data"]: ticket_data = getQueueCountAsyncResult["data"]["ticket"] ticket_split = sum(map(self.conversion_int, ticket_data.split(","))) if ticket_data.find( ",") != -1 else ticket_data print(u"排队成功, 当前余票还剩余: {0} 张".format(ticket_split)) c = confirmSingleForQueueAsys(session=self.session, passengerTicketStr=self.passengerTicketStr, oldPassengerStr=self.oldPassengerStr, result=self.result,) print(u"验证码提交安全期,等待{}MS".format(self.ifShowPassCodeTime)) time.sleep(self.ifShowPassCodeTime) c.sendConfirmSingleForQueueAsys() else: print(u"排队发现未知错误{0},将此列车 {1}加入小黑屋".format(getQueueCountAsyncResult, self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) elif "messages" in getQueueCountAsyncResult and getQueueCountAsyncResult["messages"]: print(u"排队异常,错误信息:{0}, 将此列车 {1}加入小黑屋".format(getQueueCountAsyncResult["messages"][0], self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) else: if "validateMessages" in getQueueCountAsyncResult and getQueueCountAsyncResult["validateMessages"]: print(str(getQueueCountAsyncResult["validateMessages"]))
def getRandCode(self): """ 识别验证码 :return: 坐标 """ try: if self.is_aotu_code: if self.aotu_code_type == 1: return DamatuApi(_get_yaml()["damatu"]["uesr"], _get_yaml()["damatu"]["pwd"], "./tkcode").main() elif self.aotu_code_type == 2: rc = RClient(_get_yaml()["damatu"]["uesr"], _get_yaml()["damatu"]["pwd"]) im = open('./tkcode', 'rb').read() Result = rc.rk_create(im, 6113) if "Result" in Result: return self.codexy(Ofset=",".join( list(Result["Result"])), is_raw_input=False) else: if "Error" in Result and Result["Error"]: print Result["Error"] return "" else: img = Image.open('./tkcode') img.show() return self.codexy() except: pass
def go_login_v2(self, user, passwd, rand_code=None): if self.is_auto_code and self.auto_code_type == 1: balance = DamatuApi( _get_yaml()["auto_code_account"]["user"], _get_yaml()["auto_code_account"]["pwd"]).getBalance() if int(balance) < 40: raise balanceException(u'余额不足,当前余额为: {}'.format(balance)) if not user or not passwd: raise UserPasswordException(u"温馨提示: 用户名或者密码为空,请仔细检查") login_num = 0 if rand_code is None: self.randCode = getRandCode(self.is_auto_code, self.auto_code_type) else: self.randCode = rand_code login_num += 1 self.auth() status, mess = self.codeCheck() if status: uamtk, mess = self.baseLogin(user, passwd) if uamtk: st, name = self.getUserName(uamtk) return mess, name else: return mess, ''
def readImg(self): """ 增加手动打码,只是登录接口,完全不用担心提交订单效率 思路 1.调用PIL显示图片 2.图片位置说明,验证码图片中每个图片代表一个下标,依次类推,1,2,3,4,5,6,7,8 3.控制台输入对应下标,按照英文逗号分开,即可手动完成打码, :return: """ #global randCode self.stoidinput("下载验证码...") img_path = './tkcode' r = s.get(self.captcha_url, verify=False) captcha_cookie = r.cookies.get_dict() result = r.content #print(result) try: open(img_path, 'wb').write(result) if _get_yaml(self.ticket_config)["is_aotu_code"]: #print(_get_yaml(self.ticket_config)["damatu"]["uesr"]) randCode = DamatuApi( _get_yaml(self.ticket_config)["damatu"]["uesr"], _get_yaml(self.ticket_config)["damatu"]["pwd"], img_path).main() else: img = Image.open('./tkcode') img.show() self.codexy() except OSError as e: print(e) pass return randCode
def getRandCode(is_auto_code, auto_code_type, result): """ 识别验证码 :return: 坐标 """ try: if is_auto_code: if auto_code_type == 1: print(u"打码兔已关闭, 如需使用自动识别,请使用如果平台 auto_code_type == 2") return if auto_code_type == 2: rc = RClient(_get_yaml()["auto_code_account"]["user"], _get_yaml()["auto_code_account"]["pwd"]) # im = open('./tkcode', 'rb').read() Result = rc.rk_create(result, 6113) if "Result" in Result: return codexy(Ofset=",".join(list(Result["Result"])), is_raw_input=False) else: if "Error" in Result and Result["Error"]: print( u"打码平台错误: {0}, 请登录打码平台查看-http://www.ruokuai.com/client/index?6726" .format(Result["Error"])) return "" else: img = Image.open('./tkcode') img.show() return codexy() except Exception as e: print(e)
def readImg(self, code_url): """ 增加手动打码,只是登录接口,完全不用担心提交订单效率 思路 1.调用PIL显示图片 2.图片位置说明,验证码图片中每个图片代表一个下标,依次类推,1,2,3,4,5,6,7,8 3.控制台输入对应下标,按照英文逗号分开,即可手动完成打码, :return: """ print ("下载验证码...") codeimgUrl = code_url img_path = './tkcode' result = self.httpClint.send(codeimgUrl, is_logger=False) try: open(img_path, 'wb').write(result) if self.is_aotu_code: if self.aotu_code_type == 1: return DamatuApi(_get_yaml()["damatu"]["uesr"], _get_yaml()["damatu"]["pwd"], img_path).main() elif self.aotu_code_type == 2: rc = RClient(_get_yaml()["damatu"]["uesr"], _get_yaml()["damatu"]["pwd"]) im = open('./tkcode', 'rb').read() Result = rc.rk_create(im, 6113) if "Result" in Result: return self.codexy(Ofset=",".join(list(Result["Result"])), is_raw_input=False) else: if "Error" in Result and Result["Error"]: print Result["Error"] return "" else: img = Image.open('./tkcode') img.show() return self.codexy() except OSError as e: print (e) return ""
def sendGetQueueCount(self): """ # 模拟查询当前的列车排队人数的方法 # 返回信息组成的提示字符串 :return: """ getQueueCountResult = self.session.httpClint.send(self.session.urls["getQueueCountUrl"], self.data_par()) if "status" in getQueueCountResult and getQueueCountResult["status"] is True: if "countT" in getQueueCountResult["data"]: ticket = getQueueCountResult["data"]["ticket"] ticket_split = sum(map(conversion_int, ticket.split(","))) if ticket.find(",") != -1 else ticket countT = getQueueCountResult["data"]["countT"] # if int(countT) is 0: print(u"排队成功, 你排在: {1}位, 当前余票还剩余: {0} 张".format(ticket_split, countT)) csf = confirmSingleForQueue(self.session, self.ifShowPassCodeTime, self.is_need_code, self.token, self.set_type, self.ticket_peoples, self.ticketInfoForPassengerForm, self.oldPassengerStr, self.passengerTicketStrList) csf.sendConfirmSingleForQueue() # else: # print(u"当前排队人数: {1} 当前余票还剩余:{0} 张,继续排队中".format(ticket_split, countT)) else: print(u"排队发现未知错误{0},将此列车 {1}加入小黑屋".format(getQueueCountResult, self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) elif "messages" in getQueueCountResult and getQueueCountResult["messages"]: print(u"排队异常,错误信息:{0}, 将此列车 {1}加入小黑屋".format(getQueueCountResult["messages"][0], self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) else: if "validateMessages" in getQueueCountResult and getQueueCountResult["validateMessages"]: print(str(getQueueCountResult["validateMessages"])) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) else: print(u"未知错误 {0}".format("".join(getQueueCountResult)))
def getRandCode(is_auto_code, auto_code_type, result): """ 识别验证码 :return: 坐标 """ try: if is_auto_code: if auto_code_type == 1: print(u"打码兔已关闭, 如需使用自动识别,请使用如果平台 auto_code_type == 2") return if auto_code_type == 2: rc = RClient(_get_yaml()["auto_code_account"]["user"], _get_yaml()["auto_code_account"]["pwd"]) # im = open('./tkcode', 'rb').read() Result = rc.rk_create(result, 6113) if "Result" in Result: return codexy(Ofset=",".join(list(Result["Result"])), is_raw_input=False) else: if "Error" in Result and Result["Error"]: print(u"打码平台错误: {0}, 请登录打码平台查看-http://www.ruokuai.com/client/index?6726".format(Result["Error"])) return "" else: img = Image.open('./tkcode.png') img.show() return codexy() except Exception as e: print(e)
def readImg(): """ 增加手动打码,只是登录接口,完全不用担心提交票的效率问题 思路 1.调用PIL显示图片 2.图片位置说明,验证码图片中每个图片代表一个下标,依次类推,1,2,3,4,5,6,7,8 3.控制台输入对应下标,按照英文逗号分开,即可手动完成打码, :return: """ global randCode stoidinput("下载验证码...") img_path = './tkcode' result = myurllib2.get(codeimg) try: open(img_path, 'wb').write(result) if _get_yaml()["is_aotu_code"]: randCode = DamatuApi(_get_yaml()["damatu"]["uesr"], _get_yaml()["damatu"]["pwd"], img_path).main() else: img = Image.open('./tkcode') img.show() codexy() except OSError as e: print(e) pass
def readImg(self): """ 增加手动打码,只是登录接口,完全不用担心提交订单效率 思路 1.调用PIL显示图片 2.图片位置说明,验证码图片中每个图片代表一个下标,依次类推,1,2,3,4,5,6,7,8 3.控制台输入对应下标,按照英文逗号分开,即可手动完成打码, :return: """ print("下载验证码...") codeimgUrl = self.urlConf["getCodeImg"]["req_url"] img_path = './tkcode' result = self.httpClint.send(codeimgUrl) try: open(img_path, 'wb').write(result) if _get_yaml()["is_aotu_code"]: self.randCode = DamatuApi(_get_yaml()["damatu"]["uesr"], _get_yaml()["damatu"]["pwd"], img_path).main() else: img = Image.open('./tkcode') img.show() self.codexy() except OSError as e: print(e) pass
def sendGetQueueCountAsync(self): """ 请求排队接口 :return: """ urls = self.session.urls["getQueueCountAsync"] data = self.data_par() getQueueCountAsyncResult = self.session.httpClint.send(urls, data) if getQueueCountAsyncResult.get("status", False) and getQueueCountAsyncResult.get("data", False): if "status" in getQueueCountAsyncResult and getQueueCountAsyncResult["status"] is True: if "countT" in getQueueCountAsyncResult["data"]: ticket_data = getQueueCountAsyncResult["data"]["ticket"] ticket_split = sum(map(self.conversion_int, ticket_data.split(","))) if ticket_data.find( ",") != -1 else ticket_data countT = getQueueCountAsyncResult["data"]["countT"] if int(countT) is 0: print(u"排队成功, 当前余票还剩余: {0} 张".format(ticket_split)) c = confirmSingleForQueueAsys(session=self.session, passengerTicketStr=self.passengerTicketStr, oldPassengerStr=self.oldPassengerStr, result=self.result,) print(u"验证码提交安全期,等待{}MS".format(self.ifShowPassCodeTime)) time.sleep(self.ifShowPassCodeTime) c.sendConfirmSingleForQueueAsys() else: print(u"排队发现未知错误{0},将此列车 {1}加入小黑屋".format(getQueueCountAsyncResult, self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) elif "messages" in getQueueCountAsyncResult and getQueueCountAsyncResult["messages"]: print(u"排队异常,错误信息:{0}, 将此列车 {1}加入小黑屋".format(getQueueCountAsyncResult["messages"][0], self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) else: if "validateMessages" in getQueueCountAsyncResult and getQueueCountAsyncResult["validateMessages"]: print(str(getQueueCountAsyncResult["validateMessages"]))
def __init__(self, ticket_config=""): self.captcha_url = 'https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand&%s' % random.random( ) self.ticket_config = ticket_config self.text = "" self.user = _get_yaml(ticket_config)["set"]["12306count"][0]["uesr"] self.passwd = _get_yaml(ticket_config)["set"]["12306count"][1]["pwd"] self.s = self.create_session()
def checkOrderInfo(self, train_no, set_type): """ 检查支付订单,需要提交REPEAT_SUBMIT_TOKEN passengerTicketStr : 座位编号,0,票类型,乘客名,证件类型,证件号,手机号码,保存常用联系人(Y或N) oldPassengersStr: 乘客名,证件类型,证件号,乘客类型 :return: """ passengerTicketStrList, oldPassengerStr = self.getPassengerTicketStrListAndOldPassengerStr( ) checkOrderInfoUrl = 'https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo' data = OrderedDict() data['cancel_flag'] = 2 data['bed_level_order_num'] = "000000000000000000000000000000" data['passengerTicketStr'] = self.set_type + "," + ",".join( passengerTicketStrList).rstrip("_{0}".format(self.set_type)) data['oldPassengerStr'] = "".join(oldPassengerStr) data['tour_flag'] = 'dc' data['whatsSelect'] = 1 data['REPEAT_SUBMIT_TOKEN'] = self.token checkOrderInfo = json.loads(myurllib2.Post( checkOrderInfoUrl, data, )) if 'data' in checkOrderInfo: if checkOrderInfo["data"]["ifShowPassCode"] == "y": print("需要验证码,正在使用自动识别验证码功能") for i in range(3): codeimg = 'https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=login&rand=sjrand&%s' % random.random( ) result = myurllib2.get(codeimg) img_path = './tkcode' open(img_path, 'wb').write(result) data['pass_code'] = DamatuApi( _get_yaml()["damatu"]["uesr"], _get_yaml()["damatu"]["pwd"], img_path).main() checkOrderInfo = json.loads( myurllib2.Post( checkOrderInfoUrl, data, )) if self.getQueueCount(train_no, set_type): return True else: print("验证码识别错误,第{0}次重试".format(i)) if checkOrderInfo['data']['submitStatus'] is True: print('车票提交通过,正在尝试排队') if self.getQueueCount(train_no, set_type): return True else: if "errMsg" in checkOrderInfo['data'] and checkOrderInfo[ 'data']["errMsg"]: print checkOrderInfo['data']["errMsg"] else: print checkOrderInfo elif 'messages' in checkOrderInfo and checkOrderInfo['messages']: print(checkOrderInfo['messages'][0]) print("排队失败,重新刷票中")
def go_login(self): """ 登陆 :param user: 账户名 :param passwd: 密码 :return: """ # if self.is_auto_code and self.auto_code_type == 1: # balance = DamatuApi(_get_yaml()["auto_code_account"]["user"], _get_yaml()["auto_code_account"]["pwd"]).getBalance() # if int(balance) < 40: # raise balanceException(u'余额不足,当前余额为: {}'.format(balance)) user, passwd = _get_yaml()["set"]["12306account"][0][ "user"], _get_yaml()["set"]["12306account"][1]["pwd"] if not user or not passwd: raise UserPasswordException(u"温馨提示: 用户名或者密码为空,请仔细检查") login_num = 0 while True: if loginConf(self.session): # result = getPassCodeNewOrderAndLogin(session=self.session, imgType="login") self.auth() devicesIdUrl = copy.deepcopy(self.session.urls["getDevicesId"]) devicesIdUrl["req_url"] = devicesIdUrl["req_url"].format( int(time.time() * 1000)) devicesIdRsp = self.session.httpClint.send(devicesIdUrl) devicesId = eval( devicesIdRsp.split("(")[1].split(")")[0].replace( "'", ""))["dfp"] if devicesId: self.session.httpClint.set_cookies(RAIL_DEVICEID=devicesId) result = getPassCodeNewOrderAndLogin1(session=self.session, imgType="login") if not result: continue self.randCode = getRandCode(self.is_auto_code, self.auto_code_type, result) login_num += 1 self.auth() if self.codeCheck(): uamtk = self.baseLogin(user, passwd) if uamtk: self.getUserName(uamtk) break else: loginAysnSuggest(self.session, username=user, password=passwd) login_num += 1 break # if __name__ == "__main__": # # main() # # logout()
def readImg(): global randCode stoidinput("下载验证码...") img_path = './tkcode' result = myurllib2.get(codeimg) try: open(img_path, 'wb').write(result) randCode = DamatuApi(_get_yaml()["damatu"]["uesr"], _get_yaml()["damatu"]["pwd"], img_path).main() except OSError as e: print(e) pass
def __init__(self): self.from_station, self.to_station, self.station_dates, self._station_seat, self.is_more_ticket, \ self.ticke_peoples, self.station_trains, self.ticket_black_list_time, \ self.order_type = self.get_ticket_info() self.is_auto_code = _get_yaml()["is_auto_code"] self.auto_code_type = _get_yaml()["auto_code_type"] self.is_cdn = _get_yaml()["is_cdn"] self.httpClint = HTTPClient() self.urls = urlConf.urls self.login = GoLogin(self, self.is_auto_code, self.auto_code_type) self.cdn_list = [] self.passengerTicketStrList = "" self.oldPassengerStr = ""
def sendEmail(self): """ 邮件通知 :param str: email content :return: """ email_conf = _get_yaml(self.ticket_config) is_email = email_conf["email_conf"]["is_email"] if is_email: sender = email_conf["email_conf"]["email"] receiver = email_conf["email_conf"]["notice_email_list"] subject = '恭喜,您已订票成功' username = email_conf["email_conf"]["username"] password = email_conf["email_conf"]["password"] host = email_conf["email_conf"]["host"] s = "{0}".format(self.msg) msg = MIMEText(s, 'text', 'utf-8') # 中文需参数‘utf-8’,单字节字符不需要 msg['Subject'] = Header(subject, 'utf-8') msg['From'] = sender msg['To'] = receiver smtp = smtplib.SMTP_SSL() smtp.connect(host) smtp.login(username, password) smtp.sendmail(sender, receiver.split(","), msg.as_string()) smtp.quit() print("邮件已通知, 请查收") else: pass # if __name__ == '__main__': # email.sendEmail()
def get_ticket_info(self): """ 获取配置信息 :return: """ ticket_info_config = _get_yaml() from_station = ticket_info_config["set"]["from_station"].encode("utf8") to_station = ticket_info_config["set"]["to_station"].encode("utf8") station_dates = ticket_info_config["set"]["station_dates"] set_type = ticket_info_config["set"]["set_type"] is_more_ticket = ticket_info_config["set"]["is_more_ticket"] ticke_peoples = ticket_info_config["set"]["ticke_peoples"] select_refresh_interval = ticket_info_config["select_refresh_interval"] station_trains = ticket_info_config["set"]["station_trains"] ticket_black_list_time = ticket_info_config["ticket_black_list_time"] print u"*"*20 print u"12306刷票小助手,最后更新于2018.2.28,请勿作为商业用途,交流群号:286271084" print u"如果有好的margin,请联系作者,表示非常感激\n" print u"当前配置:出发站:{0}\n到达站:{1}\n乘车日期:{2}\n坐席:{3}\n是否有票自动提交:{4}\n乘车人:{5}\n刷新间隔:{6}s(如果想随机刷新,请自行修改)\n候选购买车次:{7}\n僵尸票关小黑屋时长:{8}\n".format\ ( from_station, to_station, station_dates, ",".join(set_type), is_more_ticket, ",".join(ticke_peoples), select_refresh_interval, ",".join(station_trains), ticket_black_list_time, ) print u"*"*20 return from_station, to_station, station_dates, set_type, is_more_ticket, ticke_peoples, select_refresh_interval, station_trains, ticket_black_list_time
def __init__(self): self.from_station, self.to_station, self.station_dates, self._station_seat, self.is_more_ticket, \ self.ticke_peoples, self.station_trains, self.ticket_black_list_time, \ self.order_type, self.is_by_time, self.train_types, self.departure_time, \ self.arrival_time, self.take_time, self.order_model, self.open_time, self.is_proxy = self.get_ticket_info() self.is_auto_code = _get_yaml()["is_auto_code"] self.auto_code_type = _get_yaml()["auto_code_type"] self.is_cdn = _get_yaml()["is_cdn"] self.httpClint = HTTPClient(self.is_proxy) self.urls = urlConf.urls self.login = GoLogin(self, self.is_auto_code, self.auto_code_type) self.cdn_list = [] self.queryUrl = "leftTicket/queryZ" self.passengerTicketStrList = "" self.oldPassengerStr = "" self.set_type = ""
def sendAutoSubmitOrderRequest(self): """ 请求下单接口 :return: """ urls = self.session.urls["autoSubmitOrderRequest"] data = self.data_par() autoSubmitOrderRequestResult = self.session.httpClint.send(urls, data) if autoSubmitOrderRequestResult and \ autoSubmitOrderRequestResult.get("status", False) and\ autoSubmitOrderRequestResult.get("httpstatus", False) == 200: requestResultData = autoSubmitOrderRequestResult.get("data", {}) if requestResultData: result = requestResultData.get("result", "") ifShowPassCode = requestResultData.get("ifShowPassCode", "N") ifShowPassCodeTime = int( requestResultData.get("ifShowPassCodeTime", "1000")) / float(1000) print(ticket.AUTO_SUBMIT_ORDER_REQUEST_C) g = getQueueCountAsync( session=self.session, train_no=self.train_no, stationTrainCode=self.stationTrainCode, fromStationTelecode=self.query_from_station_name, toStationTelecode=self.query_to_station_name, leftTicket=self.leftTicket, set_type=self.set_type, users=len(self.session.ticke_peoples), station_dates=self.train_date, passengerTicketStr=self.passengerTicketStr, oldPassengerStr=self.oldPassengerStr, result=result, ifShowPassCodeTime=ifShowPassCodeTime, ) g.sendGetQueueCountAsync() if ifShowPassCode == "Y": # 如果需要验证码 print(u"需要验证码") print(u"正在使用自动识别验证码功能") for i in range(3): randCode = getRandCode( is_auto_code=True, auto_code_type=_get_yaml()["auto_code_type"]) checkcode = checkRandCodeAnsyn(self.session, randCode, "") if checkcode == 'TRUE': print(u"验证码通过,正在提交订单") data['randCode'] = randCode break else: print(u"验证码有误, {0}次尝试重试".format(i + 1)) print(u"验证码超过限定次数3次,放弃此次订票机会!") g.sendGetQueueCountAsync() else: print(ticket.AUTO_SUBMIT_ORDER_REQUEST_F) if autoSubmitOrderRequestResult.get("messages", ""): print("".join(autoSubmitOrderRequestResult.get("messages", ""))) elif autoSubmitOrderRequestResult.get("validateMessages", ""): print("".join( autoSubmitOrderRequestResult.get("validateMessages", "")))
def sendmessage(ticketmseeage: str): ''' 短信通知,调用阿里云接口 ''' message_conf = _get_yaml() is_email = message_conf["message_conf"]["is_massage"] if is_email: accessKeyId = message_conf["message_conf"]["aliyunkeyid"] aliyunsecret = message_conf["message_conf"]["aliyunsecret"] phonenumbers = message_conf["message_conf"]["phone"] trcket = '{"code":"' + ticketmseeage + '"}' client = AcsClient(accessKeyId, aliyunsecret, 'cn-hangzhou') request = CommonRequest() request.set_accept_format('json') request.set_domain('dysmsapi.aliyuncs.com') request.set_method('POST') request.set_protocol_type('https') # https | http request.set_version('2017-05-25') request.set_action_name('SendSms') request.add_query_param('RegionId', 'cn-hangzhou') request.add_query_param('PhoneNumbers', phonenumbers) request.add_query_param('SignName', '抢票小助手') request.add_query_param('TemplateCode', 'SMS_164266405') request.add_query_param('TemplateParam', trcket) response = client.do_action(request) # python2: print(response) print(str(response, encoding='utf-8')) try: pass except Exception as identifier: print(u"短信发送失败{}".format(identifier))
def sendPushBear(msg): """ pushBear微信通知 :param str: 通知内容 content :return: """ conf = _get_yaml() if conf["pushbear_conf"][ "is_pushbear"] and conf["pushbear_conf"]["send_key"].strip() != "": try: sendPushBearUrls = urls.get("Pushbear") data = { "sendkey": conf["pushbear_conf"]["send_key"].strip(), "text": "易行购票成功通知,{}".format(time.strftime("%Y-%m-%d %H:%M:%S")), "desp": msg } httpClint = HTTPClient(0) sendPushBeaRsp = httpClint.send(sendPushBearUrls, data=data) if sendPushBeaRsp.get("code") is 0: print(u"已下发 pushbear 微信通知, 请查收") else: print(sendPushBeaRsp) except Exception as e: print(u"pushbear 配置有误 {}".format(e)) else: pass
def sendEmail(msg): """ 邮件通知 :param str: email content :return: """ email_conf = _get_yaml() is_email = email_conf["email_conf"]["is_email"] if is_email: sender = email_conf["email_conf"]["email"] receiver = email_conf["email_conf"]["notice_email_list"] subject = '恭喜,您已订票成功' username = email_conf["email_conf"]["username"] password = email_conf["email_conf"]["password"] host = email_conf["email_conf"]["host"] s = "{0}".format(msg) msg = MIMEText(s, 'plain', 'utf-8') # 中文需参数‘utf-8’,单字节字符不需要 msg['Subject'] = Header(subject, 'utf-8') msg['From'] = sender msg['To'] = receiver smtp = smtplib.SMTP_SSL() smtp.connect(host) smtp.login(username, password) smtp.sendmail(sender, receiver.split(","), msg.as_string()) smtp.quit() print("邮件已通知, 请查收") else: pass
def get_ticket_info(self): """ 获取配置信息 :return: """ ticket_info_config = _get_yaml() from_station = ticket_info_config["set"]["from_station"].encode("utf8") to_station = ticket_info_config["set"]["to_station"].encode("utf8") station_dates = ticket_info_config["set"]["station_dates"] set_type = ticket_info_config["set"]["set_type"] is_more_ticket = ticket_info_config["set"]["is_more_ticket"] ticke_peoples = ticket_info_config["set"]["ticke_peoples"] station_trains = ticket_info_config["set"]["station_trains"] ticket_black_list_time = ticket_info_config["ticket_black_list_time"] order_type = ticket_info_config["order_type"] print u"*" * 20 print u"12306刷票小助手,最后更新于2018.8.31,请勿作为商业用途,交流群号:286271084" print u"如果有好的margin,请联系作者,表示非常感激\n" print u"当前配置:出发站:{0}\n到达站:{1}\n乘车日期:{2}\n坐席:{3}\n是否有票自动提交:{4}\n乘车人:{5}\n" \ u"刷新间隔:随机(1-4S)\n候选购买车次:{6}\n僵尸票关小黑屋时长:{7}\n 下单接口:{8}\n".format \ ( from_station, to_station, station_dates, ",".join(set_type), is_more_ticket, ",".join(ticke_peoples), ",".join(station_trains), ticket_black_list_time, order_type, ) print u"*" * 20 return from_station, to_station, station_dates, set_type, is_more_ticket, ticke_peoples, station_trains, ticket_black_list_time, order_type
def get_ticket_info(self): """ 获取配置信息 :return: """ ticket_info_config = _get_yaml() from_station = ticket_info_config["set"]["from_station"].encode("utf8") to_station = ticket_info_config["set"]["to_station"].encode("utf8") station_dates = ticket_info_config["set"]["station_dates"] set_type = ticket_info_config["set"]["set_type"] is_more_ticket = ticket_info_config["set"]["is_more_ticket"] ticke_peoples = ticket_info_config["set"]["ticke_peoples"] station_trains = ticket_info_config["set"]["station_trains"] ticket_black_list_time = ticket_info_config["ticket_black_list_time"] order_type = ticket_info_config["order_type"] msgs = [] msgs.append(u"*" * 20) msgs.append(u"12306刷票小助手,最后更新于2018.9.21,请勿作为商业用途,交流群号:286271084") msgs.append(u"当前配置:\n出发站:{0}\n到达站:{1}\n乘车日期:{2}\n坐席:{3}\n是否有票优先提交:{4}\n乘车人:{5}\n" \ u"刷新间隔:随机(1-3S)\n候选购买车次:{6}\n僵尸票关小黑屋时长:{7}\n 下单接口:{8}\n".format \ ( from_station, to_station, station_dates, ",".join(set_type), is_more_ticket, ",".join(ticke_peoples), ",".join(station_trains), ticket_black_list_time, order_type, )) msgs.append(u"*" * 20) print('\n'.join(msgs)) return from_station, to_station, station_dates, set_type, is_more_ticket, ticke_peoples, station_trains, ticket_black_list_time, order_type
def get_ticket_info(self): """ 获取配置信息 :return: """ ticket_info_config = _get_yaml() from_station = ticket_info_config["set"]["from_station"].encode("utf8") to_station = ticket_info_config["set"]["to_station"].encode("utf8") station_date = ticket_info_config["set"]["station_date"].encode("utf8") set_type = ticket_info_config["set"]["set_type"] is_more_ticket = ticket_info_config["set"]["is_more_ticket"] ticke_peoples = ticket_info_config["set"]["ticke_peoples"] select_refresh_interval = ticket_info_config["select_refresh_interval"] station_trains = ticket_info_config["set"]["station_trains"] expect_refresh_interval = ticket_info_config["expect_refresh_interval"] ticket_black_list_time = ticket_info_config["ticket_black_list_time"] print "*" * 20 print "当前配置:出发站:{0}\n到达站:{1}\n乘车日期:{2}\n坐席:{3}\n是否有票自动提交:{4}\n乘车人:{5}\n刷新间隔:{6}\n候选购买车次:{7}\n未开始刷票间隔时间:{8}\n僵尸票关小黑屋时长:{9}\n".format\ ( from_station, to_station, station_date, ",".join(set_type), is_more_ticket, ",".join(ticke_peoples), select_refresh_interval, ",".join(station_trains), expect_refresh_interval, ticket_black_list_time, ) print "*" * 20 return from_station, to_station, station_date, set_type, is_more_ticket, ticke_peoples, select_refresh_interval, station_trains, expect_refresh_interval, ticket_black_list_time
def __init__(self): self.from_station, self.to_station, self.station_dates, self._station_seat, self.is_more_ticket, self.ticke_peoples, self.select_refresh_interval, self.station_trains, self.ticket_black_list_time = self.get_ticket_info() self.is_aotu_code = _get_yaml()["is_aotu_code"] self.aotu_code_type = _get_yaml()["aotu_code_type"] self.order_request_params = {} # 订单提交时的参数 self.ticketInfoForPassengerForm = {} # 初始化当前页面参数 self.current_seats = {} # 席别信息 self.token = "" self.set_type = "" self.user_info = "" self.secretStr = "" self.ticket_black_list = dict() self.is_check_user = dict() self.httpClint = HTTPClient() self.confUrl = urlConf.urls self.login = GoLogin(self.httpClint, self.confUrl, self.is_aotu_code, self.aotu_code_type)
def sendEmail(msg): """ 邮件通知 :param str: email content :return: """ email_conf = _get_yaml() is_email = email_conf["email_conf"]["is_email"] if is_email: try: sender = email_conf["email_conf"]["email"] receiver = email_conf["email_conf"]["notice_email_list"] subject = '恭喜,您已订票成功' username = email_conf["email_conf"]["username"] password = email_conf["email_conf"]["password"] host = email_conf["email_conf"]["host"] s = "{0}".format(msg) msg = MIMEText(s, 'plain', 'utf-8') # 中文需参数‘utf-8’,单字节字符不需要 msg['Subject'] = Header(subject, 'utf-8') msg['From'] = sender msg['To'] = receiver smtp = smtplib.SMTP_SSL() smtp.connect(host) smtp.login(username, password) smtp.sendmail(sender, receiver.split(","), msg.as_string()) smtp.quit() print(u"邮件已通知, 请查收") except Exception as e: print(u"邮件配置有误", e.args[1].decode('gbk')) else: pass
def get_ticket_info(self): """ 获取配置信息 :return: """ ticket_info_config = _get_yaml() from_station = ticket_info_config["set"]["from_station"] to_station = ticket_info_config["set"]["to_station"] station_dates = ticket_info_config["set"]["station_dates"] set_names = ticket_info_config["set"]["set_type"] set_type = [seat_conf[x] for x in ticket_info_config["set"]["set_type"]] # set_type = [] # for x in ticket_info_config["set"]["set_type"]: # set_type.append(seat_conf[x]) # set_type = [31,30] is_more_ticket = ticket_info_config["set"]["is_more_ticket"] ticke_peoples = ticket_info_config["set"]["ticke_peoples"] station_trains = ticket_info_config["set"]["station_trains"] ticket_black_list_time = ticket_info_config["ticket_black_list_time"] order_type = ticket_info_config["order_type"] # by time is_by_time = ticket_info_config["set"]["is_by_time"] train_types = ticket_info_config["set"]["train_types"] departure_time = time_to_minutes(ticket_info_config["set"]["departure_time"]) arrival_time = time_to_minutes(ticket_info_config["set"]["arrival_time"]) take_time = time_to_minutes(ticket_info_config["set"]["take_time"]) # 下单模式 order_model = ticket_info_config["order_model"] open_time = ticket_info_config["open_time"] print(u"*" * 50) print(u"12306刷票小助手,最后更新于2019.01.02,请勿作为商业用途,交流群号:286271084(已满), 请加2群:649992274") if is_by_time: method_notie = u"购票方式:根据时间区间购票\n可接受最早出发时间:{0}\n可接受最晚抵达时间:{1}\n可接受最长旅途时间:{2}\n可接受列车类型:{3}\n" \ .format(minutes_to_time(departure_time), minutes_to_time(arrival_time), minutes_to_time(take_time), " , ".join(train_types)) else: method_notie = u"购票方式:根据候选车次购买\n候选购买车次:{0}".format(",".join(station_trains)) print (u"当前配置:\n出发站:{0}\n到达站:{1}\n乘车日期:{2}\n坐席:{3}\n是否有票优先提交:{4}\n乘车人:{5}\n" \ u"刷新间隔: 随机(1-3S)\n{6}\n僵尸票关小黑屋时长: {7}\n下单接口: {8}\n下单模式: {9}\n预售踩点时间:{10} ".format \ ( from_station, to_station, station_dates, ",".join(set_names), is_more_ticket, ",".join(ticke_peoples), method_notie, ticket_black_list_time, order_type, order_model, open_time, )) print (u"*" * 50) return from_station, to_station, station_dates, set_type, is_more_ticket, ticke_peoples, station_trains, \ ticket_black_list_time, order_type, is_by_time, train_types, departure_time, arrival_time, take_time, \ order_model, open_time
def __init__(self): self.from_station, self.to_station, self.station_dates, self._station_seat, self.is_more_ticket, self.ticke_peoples, self.select_refresh_interval, self.station_trains, self.ticket_black_list_time = self.get_ticket_info() self.is_aotu_code = _get_yaml()["is_aotu_code"] self.aotu_code_type = _get_yaml()["aotu_code_type"] self.is_cdn = _get_yaml()["is_cdn"] self.order_request_params = {} # 订单提交时的参数 self.ticketInfoForPassengerForm = {} # 初始化当前页面参数 self.current_seats = {} # 席别信息 self.token = "" self.set_type = "" self.user_info = "" self.secretStr = "" self.ticket_black_list = dict() self.is_check_user = dict() self.httpClint = HTTPClient() self.confUrl = urlConf.urls self.login = GoLogin(self.httpClint, self.confUrl, self.is_aotu_code, self.aotu_code_type) self.is_download_img = False self.randCode = "" self.cdn_list = [] self.buy_ticket_time = ""
def go_login(self): """ 登陆 :param user: 账户名 :param passwd: 密码 :return: """ if self.is_aotu_code and self.aotu_code_type == 1: balance = DamatuApi(_get_yaml()["damatu"]["uesr"], _get_yaml()["damatu"]["pwd"]).getBalance() if int(balance) < 40: raise balanceException(u'余额不足,当前余额为: {}'.format(balance)) user, passwd = _get_yaml()["set"]["12306count"][0]["uesr"], _get_yaml()["set"]["12306count"][1]["pwd"] if not user or not passwd: raise UserPasswordException(u"温馨提示: 用户名或者密码为空,请仔细检查") login_num = 0 while True: self.cookietp() self.httpClint.set_cookies(_jc_save_showIns="true", _jc_save_wfdc_flag="dc", _jc_save_fromDate=_get_yaml()["set"]["station_dates"][0], _jc_save_toDate=_get_yaml()["set"]["station_dates"][0]) self.urlConf["getCodeImg"]["req_url"] = self.urlConf["getCodeImg"]["req_url"].format(random.random()) self.readImg(self.urlConf["getCodeImg"]) self.randCode = self.getRandCode() login_num += 1 self.auth() if self.codeCheck(): uamtk = self.baseLogin(user, passwd) if uamtk: self.getUserName(uamtk) break
def sendAutoSubmitOrderRequest(self): """ 请求下单接口 :return: """ urls = self.session.urls["autoSubmitOrderRequest"] data = self.data_par() autoSubmitOrderRequestResult = self.session.httpClint.send(urls, data) if autoSubmitOrderRequestResult and \ autoSubmitOrderRequestResult.get("status", False) and\ autoSubmitOrderRequestResult.get("httpstatus", False) == 200: requestResultData = autoSubmitOrderRequestResult.get("data", {}) if requestResultData: result = requestResultData.get("result", "") ifShowPassCode = requestResultData.get("ifShowPassCode", "N") ifShowPassCodeTime = int(requestResultData.get("ifShowPassCodeTime", "1000")) / float(1000) print(ticket.AUTO_SUBMIT_ORDER_REQUEST_C) g = getQueueCountAsync(session=self.session, train_no=self.train_no, stationTrainCode=self.stationTrainCode, fromStationTelecode=self.query_from_station_name, toStationTelecode=self.query_to_station_name, leftTicket=self.leftTicket, set_type=self.set_type, users=len(self.session.ticke_peoples), station_dates=self.train_date, passengerTicketStr=self.passengerTicketStr, oldPassengerStr=self.oldPassengerStr, result=result, ifShowPassCodeTime=ifShowPassCodeTime, ) if ifShowPassCode == "Y": # 如果需要验证码 print(u"需要验证码") print(u"正在使用自动识别验证码功能") for i in range(3): randCode = getRandCode(is_auto_code=True, auto_code_type=_get_yaml()["auto_code_type"]) checkcode = checkRandCodeAnsyn(self.session, randCode, "") if checkcode == 'TRUE': print(u"验证码通过,正在提交订单") data['randCode'] = randCode break else: print (u"验证码有误, {0}次尝试重试".format(i + 1)) print(u"验证码超过限定次数3次,放弃此次订票机会!") g.sendGetQueueCountAsync() else: print(ticket.AUTO_SUBMIT_ORDER_REQUEST_F) if autoSubmitOrderRequestResult.get("messages", ""): print("".join(autoSubmitOrderRequestResult.get("messages", ""))) elif autoSubmitOrderRequestResult.get("validateMessages", ""): print("".join(autoSubmitOrderRequestResult.get("validateMessages", "")))
def sendConfirmSingleForQueue(self): """ # 模拟查询当前的列车排队人数的方法 # 返回信息组成的提示字符串 :return: """ data = self.data_par() checkQueueOrderUrl = self.session.urls["checkQueueOrderUrl"] try: if self.is_node_code: print(u"正在使用自动识别验证码功能") for i in range(3): randCode = getRandCode(is_auto_code=True, auto_code_type=_get_yaml()["auto_code_type"]) checkcode = checkRandCodeAnsyn(self.session, randCode, self.token) if checkcode == 'TRUE': print(u"验证码通过,正在提交订单") data['randCode'] = randCode break else: print (u"验证码有误, {0}次尝试重试".format(i + 1)) print(u"验证码超过限定次数3次,放弃此次订票机会!") else: print(u"不需要验证码") time.sleep(self.ifShowPassCodeTime) checkQueueOrderResult = self.session.httpClint.send(checkQueueOrderUrl, data) if "status" in checkQueueOrderResult and checkQueueOrderResult["status"]: c_data = checkQueueOrderResult["data"] if "data" in checkQueueOrderResult else {} if 'submitStatus' in c_data and c_data['submitStatus'] is True: print(u"提交订单成功!") qow = queryOrderWaitTime(self.session) qow.sendQueryOrderWaitTime() else: if 'errMsg' in c_data and c_data['errMsg']: print(u"提交订单失败,{0}".format(c_data['errMsg'])) else: print(c_data) print(u'订票失败!很抱歉,请重试提交预订功能!') elif "messages" in checkQueueOrderResult and checkQueueOrderResult["messages"]: print(u"提交订单失败,错误信息: " + checkQueueOrderResult["messages"]) else: print(u"提交订单中,请耐心等待:" + checkQueueOrderResult["message"]) except ValueError: print(u"接口 {} 无响应".format(checkQueueOrderUrl))