forked from Tlntin/JdBuyer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JdSession.py
557 lines (490 loc) · 19.4 KB
/
JdSession.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
# -*- coding:utf-8 -*-
import json
import os
import sys
import pickle
import random
import time
import requests
from pampy import match, _
from lxml import etree
DEFAULT_TIMEOUT = 10
DEFAULT_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'
if getattr(sys, 'frozen', False):
absPath = os.path.dirname(os.path.abspath(sys.executable))
elif __file__:
absPath = os.path.dirname(os.path.abspath(__file__))
class Session(object):
"""
京东买手
"""
# 初始化
def __init__(self):
self.userAgent = DEFAULT_USER_AGENT
self.headers = {'User-Agent': self.userAgent}
self.timeout = DEFAULT_TIMEOUT
self.itemDetails = dict() # 商品信息:分类id、商家id
self.username = 'jd'
self.isLogin = False
self.password = None
self.sess = requests.session()
try:
self.loadCookies()
except Exception:
pass
############## 登录相关 #############
# 保存 cookie
def saveCookies(self):
cookiesFile = os.path.join(
absPath, './cookies/{0}.cookies'.format(self.username))
directory = os.path.dirname(cookiesFile)
if not os.path.exists(directory):
os.makedirs(directory)
with open(cookiesFile, 'wb') as f:
pickle.dump(self.sess.cookies, f)
# 加载 cookie
def loadCookies(self):
cookiesFile = os.path.join(
absPath, './cookies/{0}.cookies'.format(self.username))
with open(cookiesFile, 'rb') as f:
local_cookies = pickle.load(f)
self.sess.cookies.update(local_cookies)
self.isLogin = self._validateCookies()
# 验证 cookie
def _validateCookies(self):
"""
通过访问用户订单列表页进行判断:若未登录,将会重定向到登陆页面。
:return: cookies是否有效 True/False
"""
url = 'https://order.jd.com/center/list.action'
payload = {
'rid': str(int(time.time() * 1000)),
}
try:
resp = self.sess.get(url=url, params=payload,
allow_redirects=False)
if self.respStatus(resp):
return True
except Exception as e:
return False
self.sess = requests.session()
return False
# 获取登录页
def getLoginPage(self):
url = "https://passport.jd.com/new/login.aspx"
page = self.sess.get(url, headers=self.headers)
return page
# 获取登录二维码
def getQRcode(self):
url = 'https://qr.m.jd.com/show'
payload = {
'appid': 133,
'size': 147,
't': str(int(time.time() * 1000)),
}
headers = {
'User-Agent': self.userAgent,
'Referer': 'https://passport.jd.com/new/login.aspx',
}
resp = self.sess.get(url=url, headers=headers, params=payload)
if not self.respStatus(resp):
return None
return resp.content
# 获取Ticket
def getQRcodeTicket(self):
url = 'https://qr.m.jd.com/check'
payload = {
'appid': '133',
'callback': 'jQuery{}'.format(random.randint(1000000, 9999999)),
'token': self.sess.cookies.get('wlfstk_smdl'),
'_': str(int(time.time() * 1000)),
}
headers = {
'User-Agent': self.userAgent,
'Referer': 'https://passport.jd.com/new/login.aspx',
}
resp = self.sess.get(url=url, headers=headers, params=payload)
if not self.respStatus(resp):
return False
respJson = self.parseJson(resp.text)
if respJson['code'] != 200:
return None
else:
return respJson['ticket']
# 验证Ticket
def validateQRcodeTicket(self, ticket):
url = 'https://passport.jd.com/uc/qrCodeTicketValidation'
headers = {
'User-Agent': self.userAgent,
'Referer': 'https://passport.jd.com/uc/login?ltype=logout',
}
resp = self.sess.get(url=url, headers=headers, params={'t': ticket})
if not self.respStatus(resp):
return False
respJson = json.loads(resp.text)
if respJson['returnCode'] == 0:
return True
else:
return False
############## 商品方法 #############
# 获取商品详情信息
def getItemDetail(self, skuId, skuNum=1, areaId=1):
""" 查询商品详情
:param skuId
:return 商品信息(下单模式、库存)
"""
url = 'https://item-soa.jd.com/getWareBusiness'
payload = {
'skuId': skuId,
'area': areaId,
'num': skuNum
}
resp = requests.get(url=url, params=payload, headers=self.headers)
return resp
def fetchItemDetail(self, skuId):
""" 解析商品信息
:param skuId
"""
try:
resp = self.getItemDetail(skuId).json()
# shopId = resp['shopInfo']['shop']['shopId']
shopId = match(resp, {_ :{"shopId": _}}, lambda key, value: value)
detail = dict(venderId=shopId)
# 预售商品
if 'YuShouInfo' in resp:
detail['yushouUrl'] = resp['YuShouInfo']['url']
# 秒杀商品
if 'miaoshaInfo' in resp:
detail['startTime'] = resp['miaoshaInfo']['startTime']
detail['endTime'] = resp['miaoshaInfo']['endTime']
self.itemDetails[skuId] = detail
except Exception as err:
print(err)
print("无法获取到购买信息,可能还没开抢,请等待几秒后再试")
# print("调试信息:data: ", resp)
############## 库存方法 #############
def getItemStock(self, skuId, skuNum, areaId):
"""获取单个商品库存状态
:param skuId: 商品id
:param num: 商品数量
:param areadId: 地区id
:return: 商品是否有货 True/False
"""
resp = self.getItemDetail(skuId, skuNum, areaId).json()
return 'stockInfo' in resp and resp['stockInfo']['isStock']
############## 购物车相关 #############
def uncheckCartAll(self):
""" 取消所有选中商品
return 购物车信息
"""
url = 'https://api.m.jd.com/api'
headers = {
'User-Agent': self.userAgent,
'Content-Type': 'application/x-www-form-urlencoded',
'origin': 'https://cart.jd.com',
'referer': 'https://cart.jd.com'
}
data = {
'functionId': 'pcCart_jc_cartUnCheckAll',
'appid': 'JDC_mall_cart',
'body': '{"serInfo":{"area":"","user-key":""}}',
'loginType': 3
}
resp = self.sess.post(url=url, headers=headers, data=data)
# return self.respStatus(resp) and resp.json()['success']
return resp
def addCartSku(self, skuId, skuNum):
""" 加入购入车
skuId 商品sku
skuNum 购买数量
retrun 是否成功
"""
url = 'https://api.m.jd.com/api'
headers = {
'User-Agent': self.userAgent,
'Content-Type': 'application/x-www-form-urlencoded',
'origin': 'https://cart.jd.com',
'referer': 'https://cart.jd.com'
}
data = {
'functionId': 'pcCart_jc_cartAdd',
'appid': 'JDC_mall_cart',
'body': '{\"operations\":[{\"carttype\":1,\"TheSkus\":[{\"Id\":\"' + skuId + '\",\"num\":' + str(skuNum) + '}]}]}',
'loginType': 3
}
resp = self.sess.post(url=url, headers=headers, data=data)
return self.respStatus(resp) and resp.json()['success']
def changeCartSkuCount(self, skuId, skuUid, skuNum, areaId):
""" 修改购物车商品数量
skuId 商品sku
skuUid 商品用户关系
skuNum 购买数量
retrun 是否成功
"""
url = 'https://api.m.jd.com/api'
headers = {
'User-Agent': self.userAgent,
'Content-Type': 'application/x-www-form-urlencoded',
'origin': 'https://cart.jd.com',
'referer': 'https://cart.jd.com'
}
body = '{\"operations\":[{\"TheSkus\":[{\"Id\":\"'+skuId+'\",\"num\":'+str(
skuNum)+',\"skuUuid\":\"'+skuUid+'\",\"useUuid\":false}]}],\"serInfo\":{\"area\":\"'+areaId+'\"}}'
data = {
'functionId': 'pcCart_jc_changeSkuNum',
'appid': 'JDC_mall_cart',
'body': body,
'loginType': 3
}
resp = self.sess.post(url=url, headers=headers, data=data)
return self.respStatus(resp) and resp.json()['success']
def prepareCart(self, skuId, skuNum, areaId):
""" 下单前准备购物车
1 取消全部勾选(返回购物车信息)
2 已在购物车则修改商品数量
3 不在购物车则加入购物车
skuId 商品sku
skuNum 商品数量
return True/False
"""
resp = self.uncheckCartAll()
respObj = resp.json()
if not self.respStatus(resp) or not respObj['success']:
raise Exception('购物车取消勾选失败')
# 检查商品是否已在购物车
cartInfo = respObj['resultData']['cartInfo']
if not cartInfo:
# 购物车为空 直接加入
return self.addCartSku(skuId, skuNum)
venders = cartInfo['vendors']
for vender in venders:
# if str(vender['vendorId']) != self.itemDetails[skuId]['vender_id']:
# continue
items = vender['sorted']
for item in items:
if str(item['item']['Id']) == skuId:
# 在购物车中 修改数量
return self.changeCartSkuCount(skuId, item['item']['skuUuid'], skuNum, areaId)
# 不在购物车中
return self.addCartSku(skuId, skuNum)
############## 订单相关 #############
def trySubmitOrder(self, skuId, skuNum, areaId, retry=3, interval=5):
"""提交订单
:return: 订单提交结果 True/False
"""
itemDetail = self.itemDetails[skuId]
isYushou = False
if 'yushouUrl' in itemDetail:
self.getPreSallCheckoutPage(skuId, skuNum)
isYushou = True
else:
self.prepareCart(skuId, skuNum, areaId)
self.getCheckoutPage()
for i in range(1, retry + 1):
ret, msg = self.submitOrder(isYushou)
if ret:
return True
else:
print("提交失败: ", msg)
time.sleep(interval)
return False
def submitOrderWitchTry(self, retry=3, interval=4):
"""提交订单,并且带有重试功能
:param retry: 重试次数
:param interval: 重试间隔
:return: 订单提交结果 True/False
"""
for i in range(1, retry + 1):
self.getCheckoutPage()
sumbmitSuccess, msg = self.submitOrder()
if sumbmitSuccess:
return True
else:
if i < retry:
time.sleep(interval)
return False
def getCheckoutPage(self):
"""获取订单结算页面信息
: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': self.userAgent,
'Referer': 'https://cart.jd.com/cart',
}
try:
resp = self.sess.get(url=url, params=payload, headers=headers)
if not self.respStatus(resp):
return
html = etree.HTML(resp.text)
self.eid = html.xpath("//input[@id='eid']/@value")
self.fp = html.xpath("//input[@id='fp']/@value")
self.risk_control = html.xpath("//input[@id='riskControl']/@value")
self.track_id = html.xpath("//input[@id='TrackID']/@value")
order_detail = {
# remove '寄送至: ' from the begin
'address': html.xpath("//span[@id='sendAddr']")[0].text[5:],
# remove '收件人:' from the begin
'receiver': html.xpath("//span[@id='sendMobile']")[0].text[4:],
# remove '¥' from the begin
'total_price': html.xpath("//span[@id='sumPayPriceId']")[0].text[1:],
'items': []
}
return order_detail
except Exception as e:
return
def getPreSallCheckoutPage(self, skuId, skuNum=1):
"""获取预售商品结算页面信息
:return: 结算信息 dict
"""
url = 'https://cart.jd.com/cart/dynamic/gateForSubFlow.action'
# url = 'https://cart.jd.com/gotoOrder.action'
payload = {
'wids': skuId,
'nums': skuNum,
'subType': 32
}
headers = {
'User-Agent': self.userAgent,
'Referer': 'https://cart.jd.com/cart',
}
try:
resp = self.sess.get(url=url, params=payload, headers=headers)
if not self.respStatus(resp):
return
html = etree.HTML(resp.text)
self.eid = html.xpath("//input[@id='eid']/@value")
self.fp = html.xpath("//input[@id='fp']/@value")
self.risk_control = html.xpath("//input[@id='riskControl']/@value")
self.track_id = html.xpath("//input[@id='TrackID']/@value")
order_detail = {
# remove '寄送至: ' from the begin
'address': html.xpath("//span[@class='addr-info']")[0].text,
# remove '收件人:' from the begin
'receiver': html.xpath("//span[@class='addr-name']")[0].text,
}
return order_detail
except Exception as e:
return
def submitOrder(self, isYushou=False):
"""提交订单
: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
data = {
'overseaPurchaseCookies': '',
'vendorRemarks': '[]',
'submitOrderParam.sopNotPutInvoice': 'false',
'submitOrderParam.trackID': 'TestTrackId',
'submitOrderParam.ignorePriceChange': '0',
'submitOrderParam.btSupport': '0',
'riskControl': self.risk_control,
'submitOrderParam.isBestCoupon': 1,
'submitOrderParam.jxj': 1,
'submitOrderParam.trackId': self.track_id,
'submitOrderParam.eid': self.eid,
'submitOrderParam.fp': self.fp,
'submitOrderParam.needCheck': 1,
}
if isYushou:
data['submitOrderParam.needCheck'] = 1
data['preSalePaymentTypeInOptional'] = 2
data['submitOrderParam.payType4YuShou'] = 2
# add payment password when necessary
paymentPwd = self.password
if paymentPwd:
data['submitOrderParam.payPassword'] = ''.join(
['u3' + x for x in paymentPwd])
headers = {
'User-Agent': self.userAgent,
'Host': 'trade.jd.com',
'Referer': 'http://trade.jd.com/shopping/order/getOrderInfo.action',
}
try:
resp = self.sess.post(url=url, data=data, headers=headers)
respJson = json.loads(resp.text)
if respJson.get('success'):
orderId = respJson.get('orderId')
return True, orderId
else:
message, result_code = respJson.get(
'message'), respJson.get('resultCode')
if result_code == 0:
self._saveInvoice()
message = message + '(下单商品可能为第三方商品,将切换为普通发票进行尝试)'
elif result_code == 60077:
message = message + '(可能是购物车为空 或 未勾选购物车中商品)'
elif result_code == 60123:
message = message + '(需要在config.ini文件中配置支付密码)'
return False, message
except Exception as e:
return False, e
def _saveInvoice(self):
"""下单第三方商品时如果未设置发票,将从电子发票切换为普通发票
http://jos.jd.com/api/complexTemplate.htm?webPamer=invoice&groupName=%E5%BC%80%E6%99%AE%E5%8B%92%E5%85%A5%E9%A9%BB%E6%A8%A1%E5%BC%8FAPI&id=566&restName=jd.kepler.trade.submit&isMulti=true
:return:
"""
url = 'https://trade.jd.com/shopping/dynamic/invoice/saveInvoice.action'
data = {
"invoiceParam.selectedInvoiceType": 1,
"invoiceParam.companyName": "个人",
"invoiceParam.invoicePutType": 0,
"invoiceParam.selectInvoiceTitle": 4,
"invoiceParam.selectBookInvoiceContent": "",
"invoiceParam.selectNormalInvoiceContent": 1,
"invoiceParam.vatCompanyName": "",
"invoiceParam.code": "",
"invoiceParam.regAddr": "",
"invoiceParam.regPhone": "",
"invoiceParam.regBank": "",
"invoiceParam.regBankAccount": "",
"invoiceParam.hasCommon": "true",
"invoiceParam.hasBook": "false",
"invoiceParam.consigneeName": "",
"invoiceParam.consigneePhone": "",
"invoiceParam.consigneeAddress": "",
"invoiceParam.consigneeProvince": "请选择:",
"invoiceParam.consigneeProvinceId": "NaN",
"invoiceParam.consigneeCity": "请选择",
"invoiceParam.consigneeCityId": "NaN",
"invoiceParam.consigneeCounty": "请选择",
"invoiceParam.consigneeCountyId": "NaN",
"invoiceParam.consigneeTown": "请选择",
"invoiceParam.consigneeTownId": 0,
"invoiceParam.sendSeparate": "false",
"invoiceParam.usualInvoiceId": "",
"invoiceParam.selectElectroTitle": 4,
"invoiceParam.electroCompanyName": "undefined",
"invoiceParam.electroInvoiceEmail": "",
"invoiceParam.electroInvoicePhone": "",
"invokeInvoiceBasicService": "true",
"invoice_ceshi1": "",
"invoiceParam.showInvoiceSeparate": "false",
"invoiceParam.invoiceSeparateSwitch": 1,
"invoiceParam.invoiceCode": "",
"invoiceParam.saveInvoiceFlag": 1
}
headers = {
'User-Agent': self.userAgent,
'Referer': 'https://trade.jd.com/shopping/dynamic/invoice/saveInvoice.action',
}
self.sess.post(url=url, data=data, headers=headers)
def parseJson(self, s):
begin = s.find('{')
end = s.rfind('}') + 1
return json.loads(s[begin:end])
def respStatus(self, resp):
if resp.status_code != requests.codes.OK:
return False
return True
if __name__ == '__main__':
skuId = '100015253059'
areaId = '1_2901_55554_0'
skuNum = 1
session = Session()
print(session.getItemDetail(skuId, skuNum, areaId).text)