def get_username(self):
        """获取用户信息"""
        url = 'https://passport.jd.com/user/petName/getUserInfoForMiniJd.action'
        payload = {
            'callback': 'jQuery{}'.format(random.randint(1000000, 9999999)),
            '_': str(int(time.time() * 1000)),
        }
        headers = {
            'User-Agent': self.user_agent,
            'Referer': 'https://order.jd.com/center/list.action',
        }

        resp = self.session.get(url=url, params=payload, headers=headers)

        try_count = 5
        while not resp.text.startswith("jQuery"):
            try_count = try_count - 1
            if try_count > 0:
                resp = self.session.get(url=url,
                                        params=payload,
                                        headers=headers)
            else:
                break
            wait_some_time()
        # 响应中包含了许多用户信息,现在在其中返回昵称
        # jQuery2381773({"imgUrl":"//storage.360buyimg.com/i.imageUpload/xxx.jpg","lastLoginTime":"","nickName":"xxx","plusStatus":"0","realName":"xxx","userLevel":x,"userScoreVO":{"accountScore":xx,"activityScore":xx,"consumptionScore":xxxxx,"default":false,"financeScore":xxx,"pin":"xxx","riskScore":x,"totalScore":xxxxx}})
        return parse_json(resp.text).get('nickName')
 def get_seckill_url(self):
     """获取商品的抢购链接
     点击"抢购"按钮后,会有两次302跳转,最后到达订单结算页面
     这里返回第一次跳转后的页面url,作为商品的抢购链接
     :return: 商品的抢购链接
     """
     url = 'https://itemko.jd.com/itemShowBtn'
     payload = {
         'callback': 'jQuery{}'.format(random.randint(1000000, 9999999)),
         'skuId': self.sku_id,
         'from': 'pc',
         '_': str(int(time.time() * 1000)),
     }
     headers = {
         'User-Agent': self.user_agent,
         'Host': 'itemko.jd.com',
         'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id),
     }
     while True:
         resp = self.session.get(url=url, headers=headers, params=payload)
         resp_json = parse_json(resp.text)
         if resp_json.get('url'):
             # https://divide.jd.com/user_routing?skuId=8654289&sn=c3f4ececd8461f0e4d7267e96a91e0e0&from=pc
             router_url = 'https:' + resp_json.get('url')
             # https://marathon.jd.com/captcha.html?skuId=8654289&sn=c3f4ececd8461f0e4d7267e96a91e0e0&from=pc
             seckill_url = router_url.replace('divide', 'marathon').replace(
                 'user_routing', 'captcha.html')
             logger.info("抢购链接获取成功: %s", seckill_url)
             return seckill_url
         else:
             logger.info("抢购链接获取失败,稍后自动重试")
             wait_some_time()
 def make_reserve(self):
     """商品预约"""
     logger.info('商品名称:{}'.format(self.get_sku_title()))
     url = 'https://yushou.jd.com/youshouinfo.action?'
     payload = {
         'callback': 'fetchJSON',
         'sku': self.sku_id,
         '_': str(int(time.time() * 1000)),
     }
     headers = {
         'User-Agent': self.user_agent,
         'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id),
     }
     resp = self.session.get(url=url, params=payload, headers=headers)
     resp_json = parse_json(resp.text)
     reserve_url = resp_json.get('url')
     self.timers.start()
     while True:
         try:
             self.session.get(url='https:' + reserve_url)
             logger.info('预约成功,已获得抢购资格 / 您已成功预约过了,无需重复预约')
             if global_config.getRaw('messenger', 'enable') == 'true':
                 success_message = "预约成功,已获得抢购资格 / 您已成功预约过了,无需重复预约"
                 send_wechat(success_message)
             break
         except Exception as e:
             logger.error('预约失败正在重试...')
    def _get_qrcode_ticket(self):
        """
        通过 token 获取票据
        :return:
        """
        url = 'https://qr.m.jd.com/check'
        payload = {
            'appid': '133',
            'callback': 'jQuery{}'.format(random.randint(1000000, 9999999)),
            'token': self.session.cookies.get('wlfstk_smdl'),
            '_': str(int(time.time() * 1000)),
        }
        headers = {
            'User-Agent': self.spider_session.get_user_agent(),
            'Referer': 'https://passport.jd.com/new/login.aspx',
        }
        resp = self.session.get(url=url, headers=headers, params=payload)

        if not response_status(resp):
            logger.error('获取二维码扫描结果异常')
            return False

        resp_json = parse_json(resp.text)
        if resp_json['code'] != 200:
            logger.info('Code: %s, Message: %s', resp_json['code'],
                        resp_json['msg'])
            return None
        else:
            logger.info('已完成手机客户端确认')
            return resp_json['ticket']
 def make_reserve(self):
     """商品预约"""
     logger.info('商品名称:{}'.format(self.get_sku_title()))
     url = 'https://yushou.jd.com/youshouinfo.action?'
     payload = {
         'callback': 'fetchJSON',
         'sku': self.sku_id,
         '_': str(int(time.time() * 1000)),
     }
     headers = {
         'User-Agent': self.user_agent,
         'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id),
     }
     resp = self.session.get(url=url, params=payload, headers=headers)
     resp_json = parse_json(resp.text)
     reserve_url = resp_json.get('url')
     url = 'https:' + reserve_url
     logger.info('茅台预约url:{}'.format(url))
     # self.timers.start()
     while True:
         try:
             yuyue_resp = self.session.get(url)
             if "您已成功预约过了,无需重复预约" in yuyue_resp.text:
                 logger.info('用户:{},预约成功,已获得抢购资格 / 您已成功预约过了,无需重复预约'.format(
                     self.get_username()))
             break
         except Exception as e:
             logger.error('预约失败正在重试...')
             wait_some_time()
Ejemplo n.º 6
0
    def _get_seckill_init_info(self):
        """获取秒杀初始化信息(包括:地址,发票,token)
        :return: 初始化信息组成的dict
        """
        logger.info('获取秒杀初始化信息...')
        url = 'https://marathon.jd.com/seckillnew/orderService/pc/init.action'
        data = {
            'sku': self.sku_id,
            'num': self.seckill_num,
            'isModifyAddress': 'false',
        }
        headers = {
            'User-Agent': self.user_agent,
            'Host': 'marathon.jd.com',
        }
        resp = self.session.post(url=url, data=data, headers=headers)

        resp_json = None
        try:
            resp_json = parse_json(resp.text)
        except Exception:
            logger.info('抢购失败,返回信息:{}'.format(resp.text[0:128]))
            # raise SKException('抢购失败,返回信息:{}'.format(resp.text[0: 128]))

        return resp_json
    def submit_seckill_order(self):
        """提交抢购(秒杀)订单
        :return: 抢购结果 True/False
        """
        url = 'https://marathon.jd.com/seckillnew/orderService/pc/submitOrder.action'
        payload = {
            'skuId': self.sku_id,
        }
        try:
            self.seckill_order_data[
                self.sku_id] = self._get_seckill_order_data()
        except Exception as e:
            logger.info('抢购失败,无法获取生成订单的基本信息,接口返回:【{}】'.format(str(e)))
            return False

        logger.info('提交抢购订单...')
        headers = {
            'User-Agent':
            self.user_agent,
            'Host':
            'marathon.jd.com',
            'Referer':
            'https://marathon.jd.com/seckill/seckill.action?skuId={0}&num={1}&rid={2}'
            .format(self.sku_id, self.seckill_num, int(time.time())),
        }
        resp = self.session.post(url=url,
                                 params=payload,
                                 data=self.seckill_order_data.get(self.sku_id),
                                 headers=headers)
        resp_json = None
        try:
            resp_json = parse_json(resp.text)
        except Exception as e:
            logger.info('抢购失败,返回信息:{}'.format(resp.text[0:128]))
            return False
        # 返回信息
        # 抢购失败:
        # {'errorMessage': '很遗憾没有抢到,再接再厉哦。', 'orderId': 0, 'resultCode': 60074, 'skuId': 0, 'success': False}
        # {'errorMessage': '抱歉,您提交过快,请稍后再提交订单!', 'orderId': 0, 'resultCode': 60017, 'skuId': 0, 'success': False}
        # {'errorMessage': '系统正在开小差,请重试~~', 'orderId': 0, 'resultCode': 90013, 'skuId': 0, 'success': False}
        # 抢购成功:
        # {"appUrl":"xxxxx","orderId":820227xxxxx,"pcUrl":"xxxxx","resultCode":0,"skuId":0,"success":true,"totalMoney":"xxxxx"}
        if resp_json.get('success'):
            order_id = resp_json.get('orderId')
            total_money = resp_json.get('totalMoney')
            pay_url = 'https:' + resp_json.get('pcUrl')
            logger.info('抢购成功,订单号:{}, 总价:{}, 电脑端付款链接:{}'.format(
                order_id, total_money, pay_url))
            if global_config.getRaw('messenger', 'enable') == 'true':
                success_message = "抢购成功,订单号:{}, 总价:{}, 电脑端付款链接:{}".format(
                    order_id, total_money, pay_url)
                send_wechat(success_message)
            return True
        else:
            logger.info('抢购失败,返回信息:{}'.format(resp_json))
            if global_config.getRaw('messenger', 'enable') == 'true':
                error_message = '抢购失败,返回信息:{}'.format(resp_json)
                send_wechat(error_message)
            return False
Ejemplo n.º 8
0
    def make_reserve(self):
        """商品预约"""
        logger.info('商品名称:{}'.format(self.get_sku_title()))
        url = 'https://yushou.jd.com/youshouinfo.action?'
        payload = {
            'callback': 'fetchJSON',
            'sku': self.sku_id,
            '_': str(int(time.time() * 1000)),
        }
        headers = {
            'User-Agent': self.user_agent,
            'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id),
        }
        resp = self.session.get(url=url, params=payload, headers=headers)
        resp_json = parse_json(resp.text)
        reserve_url = resp_json.get('url')
        resp.raise_for_status()
        self.timers.start()
        retry_time = 3
        is_reserve_ok = false
        while retry_time > 0:
            retry_time -= 1
            try:
                resp = self.session.get(url='https:' + reserve_url)
                if resp.status_code != 200:
                    logger.error("预约请求失败:{}, 重试中....".format( resp.status_code))
                    continue
                logger.info('预约成功,已获得抢购资格 / 您已成功预约过了,无需重复预约')
                is_reserve_ok = True
                if global_config.getRaw('messenger', 'enable') == 'true':
                    success_message = "预约成功,已获得抢购资格 / 您已成功预约过了,无需重复预约"
                    send_wechat(success_message)
                break
            except Exception as e:
                logger.error('预约失败正在重试...')

        if not is_reserve_ok:
            logger.error('预约失败...')
        return is_reserve_ok