Exemplo n.º 1
0
 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
Exemplo n.º 2
0
 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
Exemplo n.º 3
0
    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, ''
Exemplo n.º 4
0
 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
Exemplo n.º 5
0
 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
Exemplo n.º 6
0
 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 ""
Exemplo n.º 7
0
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
Exemplo n.º 8
0
    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
Exemplo n.º 9
0
 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
Exemplo n.º 10
0
 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')
Exemplo n.º 11
0
 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("排队失败,重新刷票中")
Exemplo n.º 12
0
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
Exemplo n.º 13
0
    def get_randcode(self):
        self.stoidinput("下载验证码...")
        img_path = './tkcode'
        r = self.s.get(self.captcha_url, verify=False)
        result = r.content
        # print(result)
        try:
            open(img_path, 'wb').write(result)
            if _get_yaml(self.ticket_config)["is_aotu_code"]:
                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()
                randCode = self.codexy()
        except OSError as e:
            print(e)
            pass
        print(randCode)
        return randCode
Exemplo n.º 14
0
    def checkQueueOrder(self, is_node_code=False):
        """
        模拟提交订单是确认按钮,参数获取方法还是get_ticketInfoForPassengerForm 中获取
        :return: 
        """

        passengerTicketStrList, oldPassengerStr = self.getPassengerTicketStrListAndOldPassengerStr(
        )
        checkQueueOrderUrl = "https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue"
        data = {
            "passengerTicketStr":
            self.set_type + "," + ",".join(passengerTicketStrList).rstrip(
                "_{0}".format(self.set_type)),
            "oldPassengerStr":
            "".join(oldPassengerStr),
            "purpose_codes":
            self.get_ticketInfoForPassengerForm()["purpose_codes"],
            "key_check_isChange":
            self.get_ticketInfoForPassengerForm()["key_check_isChange"],
            "leftTicketStr":
            self.get_ticketInfoForPassengerForm()["leftTicketStr"],
            "train_location":
            self.get_ticketInfoForPassengerForm()["train_location"],
            "seatDetailType":
            "000",  # 开始需要选择座位,但是目前12306不支持自动选择作为,那这个参数为默认
            "roomType":
            "00",  # 好像是根据一个id来判断选中的,两种 第一种是00,第二种是10,但是我在12306的页面没找到该id,目前写死是00,不知道会出什么错
            "dwAll":
            "N",
            "whatsSelect":
            1,
            "_json_at":
            "",
            "REPEAT_SUBMIT_TOKEN":
            self.get_token(),
        }
        try:
            for i in range(3):
                if is_node_code:
                    print("正在使用自动识别验证码功能")
                    randurl = 'https://kyfw.12306.cn/otn/passcodeNew/checkRandCodeAnsyn'
                    codeimg = 'https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=passenger&rand=randp&%s' % random.random(
                    )
                    result = myurllib2.get(codeimg)
                    img_path = './tkcode'
                    open(img_path, 'wb').write(result)
                    randCode = DamatuApi(_get_yaml()["damatu"]["uesr"],
                                         _get_yaml()["damatu"]["pwd"],
                                         img_path).main()
                    randData = {
                        "randCode": randCode,
                        "rand": "randp",
                        "_json_att": None,
                        "REPEAT_SUBMIT_TOKEN": self.get_token()
                    }
                    fresult = json.loads(myurllib2.Post(randurl, randData),
                                         encoding='utf8')  # 校验验证码是否正确
                    checkcode = fresult['data']['msg']
                    if checkcode == 'TRUE':
                        print("验证码通过,正在提交订单")
                        data['randCode'] = randCode
                        break
                    else:
                        print("验证码有误, 接口返回{0} 第{1}次尝试重试".format(fresult, i))
                else:
                    print("不需要验证码")
                    break
            # print("".join(data))
            checkQueueOrderResult = json.loads(
                myurllib2.Post(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("提交订单成功!")
                    self.queryOrderWaitTime()
                else:
                    if 'errMsg' in c_data and c_data['errMsg']:
                        print("提交订单失败,{0}".format(c_data['errMsg']))
                    else:
                        print(c_data)
                        print('订票失败!很抱歉,请重试提交预订功能!')
            elif "messages" in checkQueueOrderResult and checkQueueOrderResult[
                    "messages"]:
                print("提交订单失败,错误信息: " + checkQueueOrderResult["messages"])
            else:
                print("提交订单中,请耐心等待:" +
                      str(checkQueueOrderResult["validateMessages"]))
        except ValueError:
            print("接口 {} 无响应".format(checkQueueOrderUrl))