京东保价自动化大家在大促期间一定买了很多东西,而有些商家喜欢偷偷摸摸降价让我们觉得瞬间亏了一个亿。今天就撸一个京东的自动保价脚本。获取保价列表首先需要登录京东,这个在《618!京东PC版抢卷》上写过了,是使用二维码登录的,大家可以看看。打开京东保价页面,需要获取到下图红框中的元素,有名称,数量,购买价格。
大家在 大促期间 一定买了很多东西,而有些商家喜欢偷偷摸摸降价让我们觉得瞬间亏了一个亿。今天就撸一个京东的自动保价脚本。
获取保价列表首先需要登录京东,这个在 《618!京东PC版抢卷》上写过了,是使用二维码登录的,大家可以看看。
打开京东保价页面(https://pcsitepp-fm.jd.com/),需要获取到下图红框中的元素,有名称,数量,购买价格。
按 F12 获取下页面元素
先把全局的变量放在前面
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'session = requests.session()
下面的代码获取可以保价的订单列表包含订单号和商品的 sku 号和数量,有 3 个函数,get_pin() 函数获取 PIN 值,get_order_list() 函数循环获取订单列表,skuProResultPC() 函数判断这个订单是否超了保价时间
def get_pin():"""获取 PIN,用正则表达式从页面中取出"""url = "https://pcsitepp-fm.jd.com/"r = session.get(url)loginPin = re.findall('<input type="hidden"value="(\w )" />', r.text)pin = loginPin[0] if len(loginPin) > 0 else Nonereturn pindef get_order_list(pin, page_num=1):"""保价列表"""# 存放订单信息order_info = []# 存放数量count_dir = {}url = "https://pcsitepp-fm.jd.com/rest/pricepro/priceskusPull"data = {"page": page_num, "pageSize": 10}headers = {'User-Agent': user_agent,'Referer': 'https://pcsitepp-fm.jd.com/',}r = session.post(url, headers= headers, data=data)# 订单之间的分隔符orders = r.text.split('<tr ><td colspan="6"></td></tr>')orders.pop(0)for item in orders:# 订单号orderid = re.findall("订单号:(\d )", item)# 数量count = re.findall('<span >\n([\sx\d] )</span>',item)# 商品的 sku和序号skuidAndSequences = re.findall("queryOrderSkuPriceParam\.skuidAndSequence\.push\(\"(\d \,\d )\"\)\;", item)newSkuidAndSequences = []# 商品的sku和订单商品的序号for ss in skuidAndSequences:# 判断订单保价是否超时if skuProResultPC(orderid[0], ss.split(',')[0], pin):newSkuidAndSequences.append(ss)if orderid[0] == '117403228624':print(orderid[0])count_ss = count_html[int(ss.split(',')[1]) - 1]count = count_ss.replace('\t', '').replace('\n', '').replace('x', '')# 把 "订单号_sku" 当做 keycount_dir[orderid[0]'_'ss.split(',')[0]] = countif newSkuidAndSequences:order_info.append({'orderid': orderid[0], 'skuidAndSequence': newSkuidAndSequences})if orders:"""递归的方式获取所有的商品"""bill_info_sub, count_dir_sub = get_order_list(pin, page_num1)order_info.extend(bill_info_sub)count_dir.update(count_dir_sub)return order_info, count_dirdef skuProResultPC(orderId, skuId, pin):"""判断订单是否保价超时"""url = "https://sitepp-fm.jd.com/rest/webserver/skuProResultPC"data = {"orderId": orderId,"skuId": skuId,"pin": pin}headers = {'User-Agent': user_agent,'Referer': 'https://pcsitepp-fm.jd.com/',}r = session.post(url, data=data, headers=headers)return 'overTime' not in r.text
示例结果
订单信息:[{'orderid': '118598307636', 'skuidAndSequence': ['851267,1']}, {'orderid': '118597642910', 'skuidAndSequence': ['4389188,1']}, {'orderid': '123625659522', 'skuidAndSequence': ['69699954984,1']}, {'orderid': '123539553604', 'skuidAndSequence': ['6839875,1']}, {'orderid': '123474129967', 'skuidAndSequence': ['50000970588,1']}]商品数量{'118598307636_851267': '10', '118597642910_4389188': '10', '123625659522_69699954984': '1', '123539553604_6839875': '4', '123474129967_50000970588': '1', '122842702447_31295640649': '1', '117403228624_31295640649': '1'}
在获取保价列表中,已经取到了商品的 sku 号,在商品 url(如:https://item.jd.com/6839875.html)中最后的数字便是 sku 号,利用 sku 号可以获取到商品信息。
分析元素可知在页面的 js 中,pageConfig 变量有我们需要的所有数据,用正则表达式取出
def get_product_info(skuId):"""获商品信息"""info = {}url = "http://item.jd.com/%s.html" % skuIdheaders = {'User-Agent': user_agent,'Referer': 'https://pcsitepp-fm.jd.com/',}r = requests.get(url, headers=headers)pageConfig = re.findall("var pageConfig = \{([\s\S] )\} catch\(e\) \{\}", r.text)cat = re.findall("cat: \[([\d,] )\]", pageConfig[0])venderId = re.findall("venderId:(\d )", pageConfig[0])shopId = re.findall("shopId:'(\d )'", pageConfig[0])name = re.findall("name: '(. )'", pageConfig[0])info['cat'] = cat[0] if len(cat) else ""info['venderId'] = venderId[0] if len(venderId) else ""info['shopId'] = shopId[0] if len(shopId) else ""info['skuId'] = skuId# 配送区域默认为北京info['area'] = '1_72_55653_0'info['name'] = name[0]return info
示例结果
{'cat': '1319,1525,7057', 'venderId': '1000015389', 'shopId': '1000015389', 'skuId': '6839875', 'area': '1_72_55653_0', 'name': '雀氏chiaus薄c引力纸尿裤小号S27片(4-8kg)尿不湿新生儿柔薄透气'}{'cat': '1319,6313,15614', 'venderId': '10109166', 'shopId': '965779', 'skuId': '50000970588', 'area': '1_72_55653_0', 'name': '七彩博士 婴儿定型枕0-1岁 夏季透气天丝新生儿乳胶枕头宝宝U型枕新生儿用品 绿色天丝枕'}{'cat': '1319,1527,1559', 'venderId': '107952', 'shopId': '106328', 'skuId': '31295640649', 'area': '1_72_55653_0', 'name': 'babycare婴儿纸巾抽纸新生儿面巾纸云柔巾宝宝纸巾 108抽*6包'}
获取到商品信息后,把这些数据当做参数提交到 url(https://c0.3.cn/stock)中获取商品当前的价格。
def get_product_price(product_info):url = "https://c0.3.cn/stock?skuId={}&area={}&venderId={}&buyNum=1&choseSuitSkuIds=&cat={}&extraParam=&fqsp=0&ch=1&callback=jQuery{}"\.format(product_info['skuId'],product_info['area'],product_info['venderId'],product_info.get('cat', ''),random.randint(1000000, 9999999))headers = {'User-Agent': user_agent,'Host': 'c0.3.cn','Referer':'https://item.jd.com/{0}.html'.format(product_info['skuId']),}r = session.get(url, headers=headers)data = parse_json(r.text)# 价格price = data.get("stock", {}).get("jdPrice", {}).get('p', 0)return float(price)
在京东购物经常有满 xx 减 xx 和 满 xx 打 xx 折的优惠券,当购买商品时未使用优惠券,可以联系客服进行价格保护,这里抓取优惠券并打印出来
def get_product_coupon(product_info, price):"""优惠券列表"""result = []headers = {'User-Agent': user_agent,'Referer':'https://item.jd.com/{0}.html'.format(product_info['skuId']),}url = 'https://cd.jd.com/promotion/v2?callback=jQuery{}&skuId={}&area={}&shopId={}&venderId={}&cat={}&isCanUseDQ=1&isCanUseJQ=1&platform=0&orgType=2&jdPrice={}&appid=1&_={}'\.format(str(random.randint(1000000, 9999999)),product_info['skuId'],product_info['area'],product_info['shopId'],product_info['venderId'],product_info['cat'].replace(',', ','),price,str(int(time.time() * 1000)))r = session.get(url, headers=headers)data = parse_json(r.text)pickOneTag = data.get("prom", {}).get("pickOneTag")# 满减if pickOneTag:for tag in pickOneTag:result.append(tag.get('content'))# 打折skuCoupon = data.get('skuCoupon')if skuCoupon:for coupon in skuCoupon:if coupon.get('allDesc'):result.append(coupon.get('allDesc'))elif coupon.get('quota') and coupon.get('discount'):result.append("满"str(coupon.get('quota'))'减'str(coupon.get('discount')))return result
示例结果
['每满199元,可减100元现金,最多可减1000元', '满3件,总价打5折', '满105.0减5.0']
到这里已经取到了商品的当前价格、优惠券和购买数量,还剩下订单的下单价格需要获取,这个价格就是第一张图中的金额。我们使用订单号和 sku 号作为参数,批量查询下单价格
def get_price_list(pin):'''获取下单价格、商品信息、当前价格、数量'''product_list = []# 取订单号,sku和商品数量queryOrderPriceParam,count_dir = get_order_list(pin)# 获取购买时的价格params = {"queryOrderPriceParam": json.dumps(queryOrderPriceParam)}r = session.post("https://sitepp-fm.jd.com/rest/webserver/getOrderListSkuPrice", data = params)orderList = r.json()for item in orderList:skuid = item.get("skuid")buyingjdprice = item.get("buyingjdprice")orderid = item.get("orderid")# 商品信息product_info = get_product_info(skuid)# 当前价格price = get_product_price(product_info)# 优惠券coupon = get_product_coupon(product_info, price)name = product_info['name']count = count_dir[orderid'_'skuid]product_list.append({'orderid': orderid, 'name': name, 'price': price, 'coupon': coupon, 'count': count, 'buyingjdprice': buyingjdprice})return product_list
示例结果
[{'orderid': '123539553604', 'name': '雀氏chiaus薄c引力纸尿裤小号S27片(4-8kg)尿不湿新生儿柔薄透气', 'price': 27.9, 'coupon': ['购买1件可优惠换购热销商品', '满105.0减5.0', '满199减50', '满268减60'], 'count': '4', 'buyingjdprice': 27.0}, {'orderid': '123474129967', 'name': '七彩博士 婴儿定型枕0-1岁 夏季透气天丝新生儿乳胶枕头宝宝U型枕新生儿用品 绿色天丝枕', 'price': 69.0, 'coupon': ['06月16日 00:00 该商品参加跨店铺满折活动,满2件,总价打8折;满3件,总价打7折', '满98减5', '满105.0减5.0', '满178减10'], 'count': '1', 'buyingjdprice': 66.0}]
最后一步比价和申请价格保护,这里分为 2 种情况,一种是当前不能用优惠券可以直接申请价格保护,另一种是当前存在优惠券,可以打印到控制台通知用户。
def protect_protect_apply(product_list):"""申请价格保护"""if len(product_list) == 0:returnelse:for item in product_list:result = '订单号:{},名称:{}, 数量:{}, 购买价格:{}, 当前价格:{}, 当前优惠:{}。'\.format(item['orderid'],item['name'],item['count'],item['buyingjdprice'],item['price'],' | '.join(item['coupon']))# 没有优惠券并且购买价格高于当前价格if len(item['coupon']) == 0 and item['buyingjdprice'] > item['price']:url = 'https://pcsitepp-fm.jd.com//rest/pricepro/skuProtectApply'data = {"orderId": item['orderId'],"orderCategory": "Others","skuId": item['skuId'],"refundtype": 1}headers = {'User-Agent': user_agent,'Referer': 'https://pcsitepp-fm.jd.com/','accept': 'application/json, text/javascript, */*; q=0.01'}session.post(url, data=data, headers=headers)print(result' 已申请价格保护,请结果查看价格保护页面')elif len(item['coupon']) > 0:print(result' 在优惠券未申请自动价格保护,请联系客服申请')return
示例结果
订单号:123539553604,名称:雀氏chiaus薄c引力纸尿裤小号S27片(4-8kg)尿不湿新生儿柔薄透气, 数量:4, 购买价格:27.0, 当前价格:27.9, 当前优惠:购买1件可优惠换购热销商品 | 满105.0减5.0 | 满199减50 | 满268减60。 在优惠券未申请自动价格保护,请联系客服申请订单号:123474129967,名称:七彩博士 婴儿定型枕0-1岁 夏季透气天丝新生儿乳胶枕头宝宝U型枕新生儿用品 绿色天丝枕, 数量:1, 购买价格:66.0, 当前价格:69.0, 当前优惠:06月16日 00:00 该商品参加跨店铺满折活动,满2件,总价打8折;满3件,总价打7折 | 满98减5 | 满105.0减5.0 | 满178减10。 在优惠券未申请自动价格保护,请联系客服申请
京东自动保价的脚本核心代码已经完成了,大家可以根据自己的需求更改代码。例如增加计划任务,发送邮件而不是打印等等。感兴趣的小伙伴可以关注私信获取源码!