def cart_detail(): url = 'https://cart.jd.com/cart.action' headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", "Referer": "https://order.jd.com/center/list.action", "Host": "cart.jd.com", "Connection": "keep-alive" } resp = session.get(url, headers=headers) soup = BeautifulSoup(resp.text, "html.parser") cart_detail = dict() for item in soup.find_all(class_='item-item'): try: sku_id = item['skuid'] # 商品id except Exception as e: logger.info('购物车中有套装商品,跳过') continue try: # 例如:['increment', '8888', '100001071956', '1', '13', '0', '50067652554'] # ['increment', '8888', '100002404322', '2', '1', '0'] item_attr_list = item.find(class_='increment')['id'].split('_') p_type = item_attr_list[4] promo_id = target_id = item_attr_list[-1] if len( item_attr_list) == 7 else 0 cart_detail[sku_id] = { 'name': get_tag_value(item.select('div.p-name a')), # 商品名称 'verder_id': item['venderid'], # 商家id 'count': int(item['num']), # 数量 'unit_price': get_tag_value(item.select('div.p-price strong'))[1:], # 单价 'total_price': get_tag_value(item.select('div.p-sum strong'))[1:], # 总价 'is_selected': 'item-selected' in item['class'], # 商品是否被勾选 'p_type': p_type, 'target_id': target_id, 'promo_id': promo_id } except Exception as e: logger.error("商品%s在购物车中的信息无法解析,报错信息: %s,该商品自动忽略", sku_id, e) logger.info('购物车信息:%s', cart_detail) return cart_detail
def add_item_to_cart(sku_id): url = 'https://cart.jd.com/gate.action' payload = { 'pid': sku_id, 'pcount': 1, 'ptype': 1, } resp = session.get(url=url, params=payload) if 'https://cart.jd.com/cart.action' in resp.url: # 套装商品加入购物车后直接跳转到购物车页面 result = True else: # 普通商品成功加入购物车后会跳转到提示 "商品已成功加入购物车!" 页面 soup = BeautifulSoup(resp.text, "html.parser") result = bool(soup.select('h3.ftx-02')) # [<h3 class="ftx-02">商品已成功加入购物车!</h3>] if result: logger.info('%s 已成功加入购物车', sku_id) else: logger.error('%s 添加到购物车失败', sku_id)
def checkLogin(self): # 恢复之前保存的cookie checkUrl = 'https://passport.jd.com/uc/qrCodeTicketValidation' try: print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++') print(f'{time.ctime()} > 检查登录状态中... ') with open('cookie', 'rb') as f: cookies = requests.utils.cookiejar_from_dict(pickle.load(f)) response = requests.get(checkUrl, cookies=cookies) if response.status_code != requests.codes.OK: print('登录过期, 请重新登录!') return False else: print('登陆状态正常') self.cookies.update(dict(cookies)) return True except Exception as e: logger.error(e) return False
def get_checkout_page_detail(): """获取订单结算页面信息 该方法会返回订单结算页面的详细信息:商品名称、价格、数量、库存状态等。 :return: 结算信息 dict """ url = 'http://trade.jd.com/shopping/order/getOrderInfo.action' # url = 'https://cart.jd.com/gotoOrder.action' payload = { 'rid': str(int(time.time() * 1000)), } headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", "Referer": "https://cart.jd.com/cart.action", "Connection": "keep-alive", 'Host': 'trade.jd.com', } try: resp = session.get(url=url, params=payload, headers=headers) if not response_status(resp): logger.error('获取订单结算页信息失败') return '' soup = BeautifulSoup(resp.text, "html.parser") risk_control = get_tag_value(soup.select('input#riskControl'), 'value') order_detail = { 'address': soup.find('span', id='sendAddr').text[5:], # remove '寄送至: ' from the begin 'receiver': soup.find( 'span', id='sendMobile').text[4:], # remove '收件人:' from the begin 'total_price': soup.find( 'span', id='sumPayPriceId').text[1:], # remove '¥' from the begin 'items': [] } logger.info("下单信息:%s", order_detail) return order_detail except requests.exceptions.RequestException as e: logger.error('订单结算页面获取异常:%s' % e) except Exception as e: logger.error('下单页面数据解析异常:%s', e) return risk_control
def sendWechat(sc_key, text='京东商品监控', desp=''): if not text.strip(): logger.error('Text of message is empty!') return now_time = str(datetime.datetime.now()) desp = '[{0}]'.format(now_time) if not desp else '{0} [{1}]'.format( desp, now_time) try: resp = requests.get( 'https://sc.ftqq.com/{}.send?text={}&desp={}'.format( sc_key, text, desp)) resp_json = json.loads(resp.text) if resp_json.get('errno') == 0: logger.info('Message sent successfully [text: %s, desp: %s]', text, desp) else: logger.error('Fail to send message, reason: %s', resp.text) except requests.exceptions.RequestException as req_error: logger.error('Request error: %s', req_error) except Exception as e: logger.error('Fail to send message [text: %s, desp: %s]: %s', text, desp, e)
def submit_order(risk_control): """提交订单 重要: 1.该方法只适用于普通商品的提交订单(即可以加入购物车,然后结算提交订单的商品) 2.提交订单时,会对购物车中勾选✓的商品进行结算(如果勾选了多个商品,将会提交成一个订单) :return: True/False 订单提交结果 """ url = 'https://trade.jd.com/shopping/order/submitOrder.action' # js function of submit order is included in https://trade.jd.com/shopping/misc/js/order.js?r=2018070403091 # overseaPurchaseCookies: # vendorRemarks: [] # submitOrderParam.sopNotPutInvoice: false # submitOrderParam.trackID: TestTrackId # submitOrderParam.ignorePriceChange: 0 # submitOrderParam.btSupport: 0 # riskControl: # submitOrderParam.isBestCoupon: 1 # submitOrderParam.jxj: 1 # submitOrderParam.trackId: data = { 'overseaPurchaseCookies': '', 'vendorRemarks': '[]', 'submitOrderParam.sopNotPutInvoice': 'false', 'submitOrderParam.trackID': 'TestTrackId', 'submitOrderParam.ignorePriceChange': '0', 'submitOrderParam.btSupport': '0', 'riskControl': risk_control, 'submitOrderParam.isBestCoupon': 1, 'submitOrderParam.jxj': 1, 'submitOrderParam.trackId': '9643cbd55bbbe103eef18a213e069eb0', # Todo: need to get trackId # 'submitOrderParam.eid': eid, # 'submitOrderParam.fp': fp, 'submitOrderParam.needCheck': 1, } def encrypt_payment_pwd(payment_pwd): return ''.join(['u3' + x for x in payment_pwd]) if len(payment_pwd) > 0: data['submitOrderParam.payPassword'] = encrypt_payment_pwd(payment_pwd) headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", "Referer": "http://trade.jd.com/shopping/order/getOrderInfo.action", "Connection": "keep-alive", 'Host': 'trade.jd.com', } try: resp = session.post(url=url, data=data, headers=headers) resp_json = json.loads(resp.text) # 返回信息示例: # 下单失败 # {'overSea': False, 'orderXml': None, 'cartXml': None, 'noStockSkuIds': '', 'reqInfo': None, 'hasJxj': False, 'addedServiceList': None, 'sign': None, 'pin': 'xxx', 'needCheckCode': False, 'success': False, 'resultCode': 60123, 'orderId': 0, 'submitSkuNum': 0, 'deductMoneyFlag': 0, 'goJumpOrderCenter': False, 'payInfo': None, 'scaleSkuInfoListVO': None, 'purchaseSkuInfoListVO': None, 'noSupportHomeServiceSkuList': None, 'msgMobile': None, 'addressVO': None, 'msgUuid': None, 'message': '请输入支付密码!'} # {'overSea': False, 'cartXml': None, 'noStockSkuIds': '', 'reqInfo': None, 'hasJxj': False, 'addedServiceList': None, 'orderXml': None, 'sign': None, 'pin': 'xxx', 'needCheckCode': False, 'success': False, 'resultCode': 60017, 'orderId': 0, 'submitSkuNum': 0, 'deductMoneyFlag': 0, 'goJumpOrderCenter': False, 'payInfo': None, 'scaleSkuInfoListVO': None, 'purchaseSkuInfoListVO': None, 'noSupportHomeServiceSkuList': None, 'msgMobile': None, 'addressVO': None, 'msgUuid': None, 'message': '您多次提交过快,请稍后再试'} # {'overSea': False, 'orderXml': None, 'cartXml': None, 'noStockSkuIds': '', 'reqInfo': None, 'hasJxj': False, 'addedServiceList': None, 'sign': None, 'pin': 'xxx', 'needCheckCode': False, 'success': False, 'resultCode': 60077, 'orderId': 0, 'submitSkuNum': 0, 'deductMoneyFlag': 0, 'goJumpOrderCenter': False, 'payInfo': None, 'scaleSkuInfoListVO': None, 'purchaseSkuInfoListVO': None, 'noSupportHomeServiceSkuList': None, 'msgMobile': None, 'addressVO': None, 'msgUuid': None, 'message': '获取用户订单信息失败'} # {"cartXml":null,"noStockSkuIds":"xxx","reqInfo":null,"hasJxj":false,"addedServiceList":null,"overSea":false,"orderXml":null,"sign":null,"pin":"xxx","needCheckCode":false,"success":false,"resultCode":600157,"orderId":0,"submitSkuNum":0,"deductMoneyFlag":0,"goJumpOrderCenter":false,"payInfo":null,"scaleSkuInfoListVO":null,"purchaseSkuInfoListVO":null,"noSupportHomeServiceSkuList":null,"msgMobile":null,"addressVO":{"pin":"xxx","areaName":"","provinceId":xx,"cityId":xx,"countyId":xx,"townId":xx,"paymentId":0,"selected":false,"addressDetail":"xx","mobile":"xx","idCard":"","phone":null,"email":null,"selfPickMobile":null,"selfPickPhone":null,"provinceName":null,"cityName":null,"countyName":null,"townName":null,"giftSenderConsigneeName":null,"giftSenderConsigneeMobile":null,"gcLat":0.0,"gcLng":0.0,"coord_type":0,"longitude":0.0,"latitude":0.0,"selfPickOptimize":0,"consigneeId":0,"selectedAddressType":0,"siteType":0,"helpMessage":null,"tipInfo":null,"cabinetAvailable":true,"limitKeyword":0,"specialRemark":null,"siteProvinceId":0,"siteCityId":0,"siteCountyId":0,"siteTownId":0,"skuSupported":false,"addressSupported":0,"isCod":0,"consigneeName":null,"pickVOname":null,"shipmentType":0,"retTag":0,"tagSource":0,"userDefinedTag":null,"newProvinceId":0,"newCityId":0,"newCountyId":0,"newTownId":0,"newProvinceName":null,"newCityName":null,"newCountyName":null,"newTownName":null,"checkLevel":0,"optimizePickID":0,"pickType":0,"dataSign":0,"overseas":0,"areaCode":null,"nameCode":null,"appSelfPickAddress":0,"associatePickId":0,"associateAddressId":0,"appId":null,"encryptText":null,"certNum":null,"used":false,"oldAddress":false,"mapping":false,"addressType":0,"fullAddress":"xxxx","postCode":null,"addressDefault":false,"addressName":null,"selfPickAddressShuntFlag":0,"pickId":0,"pickName":null,"pickVOselected":false,"mapUrl":null,"branchId":0,"canSelected":false,"address":null,"name":"xxx","message":null,"id":0},"msgUuid":null,"message":"xxxxxx商品无货"} # {'orderXml': None, 'overSea': False, 'noStockSkuIds': 'xxx', 'reqInfo': None, 'hasJxj': False, 'addedServiceList': None, 'cartXml': None, 'sign': None, 'pin': 'xxx', 'needCheckCode': False, 'success': False, 'resultCode': 600158, 'orderId': 0, 'submitSkuNum': 0, 'deductMoneyFlag': 0, 'goJumpOrderCenter': False, 'payInfo': None, 'scaleSkuInfoListVO': None, 'purchaseSkuInfoListVO': None, 'noSupportHomeServiceSkuList': None, 'msgMobile': None, 'addressVO': {'oldAddress': False, 'mapping': False, 'pin': 'xxx', 'areaName': '', 'provinceId': xx, 'cityId': xx, 'countyId': xx, 'townId': xx, 'paymentId': 0, 'selected': False, 'addressDetail': 'xxxx', 'mobile': 'xxxx', 'idCard': '', 'phone': None, 'email': None, 'selfPickMobile': None, 'selfPickPhone': None, 'provinceName': None, 'cityName': None, 'countyName': None, 'townName': None, 'giftSenderConsigneeName': None, 'giftSenderConsigneeMobile': None, 'gcLat': 0.0, 'gcLng': 0.0, 'coord_type': 0, 'longitude': 0.0, 'latitude': 0.0, 'selfPickOptimize': 0, 'consigneeId': 0, 'selectedAddressType': 0, 'newCityName': None, 'newCountyName': None, 'newTownName': None, 'checkLevel': 0, 'optimizePickID': 0, 'pickType': 0, 'dataSign': 0, 'overseas': 0, 'areaCode': None, 'nameCode': None, 'appSelfPickAddress': 0, 'associatePickId': 0, 'associateAddressId': 0, 'appId': None, 'encryptText': None, 'certNum': None, 'addressType': 0, 'fullAddress': 'xxxx', 'postCode': None, 'addressDefault': False, 'addressName': None, 'selfPickAddressShuntFlag': 0, 'pickId': 0, 'pickName': None, 'pickVOselected': False, 'mapUrl': None, 'branchId': 0, 'canSelected': False, 'siteType': 0, 'helpMessage': None, 'tipInfo': None, 'cabinetAvailable': True, 'limitKeyword': 0, 'specialRemark': None, 'siteProvinceId': 0, 'siteCityId': 0, 'siteCountyId': 0, 'siteTownId': 0, 'skuSupported': False, 'addressSupported': 0, 'isCod': 0, 'consigneeName': None, 'pickVOname': None, 'shipmentType': 0, 'retTag': 0, 'tagSource': 0, 'userDefinedTag': None, 'newProvinceId': 0, 'newCityId': 0, 'newCountyId': 0, 'newTownId': 0, 'newProvinceName': None, 'used': False, 'address': None, 'name': 'xx', 'message': None, 'id': 0}, 'msgUuid': None, 'message': 'xxxxxx商品无货'} # 下单成功 # {'overSea': False, 'orderXml': None, 'cartXml': None, 'noStockSkuIds': '', 'reqInfo': None, 'hasJxj': False, 'addedServiceList': None, 'sign': None, 'pin': 'xxx', 'needCheckCode': False, 'success': True, 'resultCode': 0, 'orderId': 8740xxxxx, 'submitSkuNum': 1, 'deductMoneyFlag': 0, 'goJumpOrderCenter': False, 'payInfo': None, 'scaleSkuInfoListVO': None, 'purchaseSkuInfoListVO': None, 'noSupportHomeServiceSkuList': None, 'msgMobile': None, 'addressVO': None, 'msgUuid': None, 'message': None} if resp_json.get('success'): logger.info('订单提交成功! 订单号:%s', resp_json.get('orderId')) return True else: message, result_code = resp_json.get('message'), resp_json.get( 'resultCode') if result_code == 0: # self._save_invoice() message = message + '(下单商品可能为第三方商品,将切换为普通发票进行尝试)' elif result_code == 60077: message = message + '(可能是购物车为空 或 未勾选购物车中商品)' elif result_code == 60123: message = message + '(需要在payment_pwd参数配置支付密码)' logger.info('订单提交失败, 错误码:%s, 返回信息:%s', result_code, message) logger.info(resp_json) return False except Exception as e: logger.error(e) return False
print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++') time.sleep(2) ''' 需要修改 ''' #cookies在单独文件中保存 通过扫二维码登陆获取并自动保存 # 简洁模式 pure = global_config.getRaw('config', 'pure_mode') pure_mode=False if(pure != "0"): print("简洁模式已开启") pure_mode=True #最大检测商品线程数量 thread_max_nums = int(global_config.getRaw('config', 'thread_max_nums')) if(thread_max_nums<2): logger.error('config.ini文件中输入的thread_max_nums有误!最小为2!') sys.exit(1) # 方糖微信推送的key 不知道的请看http://sc.ftqq.com/3.version sc_key = global_config.getRaw('config', 'sc_key') # 推送方式 1(mail)或 2(wechat) messageType = str(global_config.getRaw('config', 'messageType')) #cookies在单独文件中保存 通过扫二维码登陆获取并自动保存 # 有货通知 收件邮箱 mail = global_config.getRaw('config', 'mail') # 地区id area = str(global_config.getRaw('config', 'area')).replace("-","_").replace(" ","") print(area) # 商品id skuidsString = global_config.getRaw('config', 'skuids') skuids = str(skuidsString).split(',') logger.info("["+str(len(skuids))+"]个需要检测的商品")
cookies_String = global_config.getRaw('config', 'cookies_String') # 有货通知 收件邮箱 mail = global_config.getRaw('config', 'mail') # 方糖微信推送的key 不知道的请看http://sc.ftqq.com/3.version sc_key = global_config.getRaw('config', 'sc_key') # 推送方式 1(mail)或 2(wechat) messageTtpe = global_config.getRaw('config', 'messageTtpe') # 地区id area = global_config.getRaw('config', 'area') # 商品id skuidsString = global_config.getRaw('config', 'skuids') skuids = str(skuidsString).split(',') if len(skuids[0]) == 0: logger.error('请在config.ini文件中输入你的商品id') sys.exit(1) message = message(messageTtpe=messageTtpe, sc_key=sc_key, mail=mail) ''' 备用 ''' # eid eid = global_config.getRaw('config', 'eid') fp = global_config.getRaw('config', 'fp') # 支付密码 payment_pwd = global_config.getRaw('config', 'payment_pwd') session = requests.session() session.headers = { "User-Agent":