forked from tychxn/jd-assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjd_assistant.py
1143 lines (1007 loc) · 51.9 KB
/
jd_assistant.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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import random
import requests
import pickle
from bs4 import BeautifulSoup
from util import *
from timer import Timer
from config import global_config
class Assistant(object):
def __init__(self):
self.username = ''
self.nick_name = ''
self.is_login = False
self.headers = {
'User-Agent': USER_AGENT,
}
self.sess = requests.session()
self.item_cat = dict()
self.risk_control = ''
self.eid = global_config.get('config', 'eid') or DEFAULT_EID
self.fp = global_config.get('config', 'fp') or DEFAULT_FP
self.track_id = '9643cbd55bbbe103eef18a213e069eb0'
self.seckill_init_info = dict()
self.seckill_order_data = dict()
self.seckill_url = dict()
try:
self._load_cookies()
except Exception as e:
pass
def _load_cookies(self):
cookies_file = ''
for name in os.listdir('./cookies'):
if name.endswith('.cookies'):
cookies_file = './cookies/{0}'.format(name)
break
with open(cookies_file, 'rb') as f:
local_cookies = pickle.load(f)
self.sess.cookies.update(local_cookies)
self.is_login = self._validate_cookies()
def _save_cookies(self):
cookies_file = './cookies/{0}.cookies'.format(self.nick_name)
directory = os.path.dirname(cookies_file)
if not os.path.exists(directory):
os.makedirs(directory)
with open(cookies_file, 'wb') as f:
pickle.dump(self.sess.cookies, f)
def _validate_cookies(self): # True -- cookies is valid, False -- cookies is invalid
# user can't access to order list page (would redirect to login page) if his cookies is expired
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 resp.status_code == requests.codes.OK:
return True
except Exception as e:
print(get_current_time(), e)
self.sess = requests.session()
return False
def _need_auth_code(self, username):
url = 'https://passport.jd.com/uc/showAuthCode'
data = {
'loginName': username,
}
payload = {
'version': 2015,
'r': random.random(),
}
resp = self.sess.post(url, params=payload, data=data, headers=self.headers)
if not response_status(resp):
print('获取是否需要验证码失败')
return False
js = json.loads(resp.text[1:-1]) # ({"verifycode":true})
return js['verifycode']
def _get_auth_code(self, uuid):
image_file = os.path.join(os.getcwd(), 'jd_authcode.jpg')
url = 'https://authcode.jd.com/verify/image'
payload = {
'a': 1,
'acid': uuid,
'uid': uuid,
'yys': str(int(time.time() * 1000)),
}
headers = {
'User-Agent': USER_AGENT,
'Referer': 'https://passport.jd.com/uc/login',
}
resp = self.sess.get(url, params=payload, headers=headers)
if not response_status(resp):
print('获取验证码失败')
return ''
save_image(resp, image_file)
open_image(image_file)
return input('验证码:')
def _get_login_page(self):
url = "https://passport.jd.com/new/login.aspx"
page = self.sess.get(url, headers=self.headers)
return page
def _get_login_data(self):
page = self._get_login_page()
soup = BeautifulSoup(page.text, "html.parser")
input_list = soup.select('.form input')
data = dict()
data['sa_token'] = input_list[0]['value']
data['uuid'] = input_list[1]['value']
data['_t'] = input_list[4]['value']
data['loginType'] = input_list[5]['value']
data['pubKey'] = input_list[7]['value']
# eid & fp are generated by local javascript code according to browser environment
data['eid'] = self.eid
data['fp'] = self.fp
return data
def login_by_username(self):
if self.is_login:
print(get_current_time(), '登录成功')
return
username = input('账号:')
password = input('密码:')
if (not username) or (not password):
print(get_current_time(), '用户名或密码不能为空')
return
self.username = username
data = self._get_login_data()
uuid = data['uuid']
auth_code = ''
if self._need_auth_code(username):
print(get_current_time(), '本次登录需要验证码')
auth_code = self._get_auth_code(uuid)
else:
print(get_current_time(), '本次登录不需要验证码')
login_url = "https://passport.jd.com/uc/loginService"
payload = {
'uuid': uuid,
'version': 2015,
'r': random.random(),
}
data['authcode'] = auth_code
data['loginname'] = username
data['nloginpwd'] = encrypt_pwd(password)
headers = {
'User-Agent': USER_AGENT,
'Origin': 'https://passport.jd.com',
}
resp = self.sess.post(url=login_url, data=data, headers=headers, params=payload)
if not response_status(resp):
print(get_current_time(), '登录失败')
return False
if not self._get_login_result(resp):
return False
# login success
print(get_current_time(), '登录成功')
self.nick_name = self.get_user_info()
self._save_cookies()
self.is_login = True
return True
def _get_login_result(self, resp):
js = parse_json(resp.text)
error_msg = ''
if 'success' in js:
# {"success":"http://www.jd.com"}
return True
elif 'emptyAuthcode' in js:
# {'_t': '_t', 'emptyAuthcode': '请输入验证码'}
# {'_t': '_t', 'emptyAuthcode': '验证码不正确或验证码已过期'}
error_msg = js['emptyAuthcode']
elif 'username' in js:
# {'_t': '_t', 'username': '账户名不存在,请重新输入'}
# {'username': '服务器繁忙,请稍后再试', 'venture': 'xxxx', 'p': 'xxxx', 'ventureRet': 'http://www.jd.com/', '_t': '_t'}
if js['username'] == '服务器繁忙,请稍后再试':
error_msg = js['username'] + '(预计账户存在风险,需短信激活)'
else:
error_msg = js['username']
elif 'pwd' in js:
# {'pwd': '账户名与密码不匹配,请重新输入', '_t': '_t'}
error_msg = js['pwd']
else:
error_msg = js
print(get_current_time(), error_msg)
return False
def _get_QRcode(self):
url = 'https://qr.m.jd.com/show'
payload = {
'appid': 133,
'size': 147,
't': str(int(time.time() * 1000)),
}
headers = {
'User-Agent': USER_AGENT,
'Referer': 'https://passport.jd.com/new/login.aspx',
}
resp = self.sess.get(url=url, headers=headers, params=payload)
if not response_status(resp):
print(get_current_time(), '获取二维码失败')
return False
QRCode_file = 'QRcode.png'
save_image(resp, QRCode_file)
print(get_current_time(), '二维码获取成功,请打开京东APP扫描')
open_image(QRCode_file)
return True
def _get_QRcode_ticket(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': USER_AGENT,
'Referer': 'https://passport.jd.com/new/login.aspx',
}
resp = self.sess.get(url=url, headers=headers, params=payload)
if not response_status(resp):
print(get_current_time(), '获取二维码扫描结果出错')
return False
js = parse_json(resp.text)
if js['code'] != 200:
print(get_current_time(), 'Code: {0}, Message: {1}'.format(js['code'], js['msg']))
return None
else:
print(get_current_time(), '已完成手机客户端确认')
return js['ticket']
def _validate_QRcode_ticket(self, ticket):
url = 'https://passport.jd.com/uc/qrCodeTicketValidation'
headers = {
'User-Agent': USER_AGENT,
'Referer': 'https://passport.jd.com/uc/login?ltype=logout',
}
resp = self.sess.get(url=url, headers=headers, params={'t': ticket})
if not response_status(resp):
return False
js = json.loads(resp.text)
if js['returnCode'] == 0:
return True
else:
print(get_current_time(), js)
return False
def login_by_QRcode(self):
"""二维码登陆
:return:
"""
if self.is_login:
print(get_current_time(), '登录成功')
return True
self._get_login_page()
# download QR code
if not self._get_QRcode():
print(get_current_time(), '登录失败')
return False
# get QR code ticket
ticket = None
retry_times = 90
for _ in range(retry_times):
ticket = self._get_QRcode_ticket()
if ticket:
break
time.sleep(2)
else:
print(get_current_time(), '二维码扫描出错')
return False
# validate QR code ticket
if not self._validate_QRcode_ticket(ticket):
print(get_current_time(), '二维码登录失败')
return False
else:
print(get_current_time(), '二维码登录成功')
self.nick_name = self.get_user_info()
self._save_cookies()
self.is_login = True
return True
def _get_reserve_url(self, sku_id):
url = 'https://yushou.jd.com/youshouinfo.action'
payload = {
'callback': 'fetchJSON',
'sku': sku_id,
}
headers = {
'User-Agent': USER_AGENT,
'Referer': 'https://item.jd.com/{}.html'.format(sku_id),
}
resp = self.sess.get(url=url, params=payload, headers=headers)
js = parse_json(resp.text)
# {"type":"1","hasAddress":false,"riskCheck":"0","flag":false,"num":941723,"stime":"2018-10-12 12:40:00","plusEtime":"","qiangEtime":"","showPromoPrice":"0","qiangStime":"","state":2,"sku":100000287121,"info":"\u9884\u7ea6\u8fdb\u884c\u4e2d","isJ":0,"address":"","d":48824,"hidePrice":"0","yueEtime":"2018-10-19 15:01:00","plusStime":"","isBefore":0,"url":"//yushou.jd.com/toYuyue.action?sku=100000287121&key=237af0174f1cffffd227a2f98481a338","etime":"2018-10-19 15:01:00","plusD":48824,"category":"4","plusType":0,"yueStime":"2018-10-12 12:40:00"};
reserve_url = js.get('url')
return 'https:' + reserve_url if reserve_url else None
def make_reserve(self, sku_id):
"""商品预约
:param sku_id: 商品id
:return:
"""
reserve_url = self._get_reserve_url(sku_id)
if not reserve_url:
print(get_current_time(), '{} 非预约商品'.format(sku_id))
return
headers = {
'User-Agent': USER_AGENT,
'Referer': 'https://item.jd.com/{}.html'.format(sku_id),
}
resp = self.sess.get(url=reserve_url, headers=headers)
soup = BeautifulSoup(resp.text, "html.parser")
reserve_result = soup.find('p', {'class': 'bd-right-result'}).text.strip(' \t\r\n')
# 预约成功,已获得抢购资格 / 您已成功预约过了,无需重复预约
print(get_current_time(), reserve_result)
def get_user_info(self):
"""获取用户信息
:return: 用户名
"""
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': USER_AGENT,
'Referer': 'https://order.jd.com/center/list.action',
}
try:
resp = self.sess.get(url=url, params=payload, headers=headers)
js = parse_json(resp.text)
# many user info are included in response, now return nick name in it
# 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 js.get('nickName') or 'jd'
except Exception as e:
return 'jd'
def _get_item_detail_page(self, sku_id):
"""访问商品详情页
:param sku_id: 商品id
:return: 响应
"""
url = 'https://item.jd.com/{}.html'.format(sku_id)
page = requests.get(url=url, headers=self.headers)
return page
def get_single_item_stock(self, sku_id, area):
"""获取单个商品库存状态
:param sku_id: 商品id
:param area: 地区id
:return: 库存状态元祖:(33, '现货') (34, '无货') (36, '采购中') (40, '可配货')
"""
cat = self.item_cat.get(sku_id)
if not cat:
page = self._get_item_detail_page(sku_id)
m = re.search(r'cat: \[(.*?)\]', page.text)
cat = m.group(1)
self.item_cat[sku_id] = cat
url = 'https://c0.3.cn/stock'
payload = {
'skuId': sku_id,
'buyNum': 1,
'area': area,
'ch': 1,
'_': str(int(time.time() * 1000)),
'callback': 'jQuery{}'.format(random.randint(1000000, 9999999)),
'extraParam': '{"originid":"1"}', # get error stock state without this param
'cat': cat, # get 403 Forbidden without this param (obtained from the detail page)
# 'venderId': '' # won't return seller information without this param (can be ignored)
}
headers = {
'User-Agent': USER_AGENT,
'Referer': 'https://item.jd.com/{}.html'.format(sku_id),
}
resp = requests.get(url=url, params=payload, headers=headers)
js = parse_json(resp.text)
stock_state = js['StockState'] # 33 -- 现货 34 -- 无货 40 -- 可配货
stock_state_name = js['StockStateName']
return stock_state, stock_state_name # (33, '现货') (34, '无货') (36, '采购中') (40, '可配货')
def get_multi_item_stock(self, sku_ids, area):
"""获取多个商品库存状态
该方法需要登陆才能调用,用于同时查询多个商品的库存。
京东查询接口返回每种商品的状态:有货/无货。当所有商品都有货,返回True;否则,返回False。
:param sku_ids: 多个商品的id。可以传入中间用英文逗号的分割字符串,如"123,456";或传入商品列表,如["123", "456"]
:param area: 地区id
:return: 多个商品是否同时有货 True/False
"""
if not isinstance(sku_ids, list):
sku_ids = parse_sku_id(sku_ids=sku_ids)
area_code = parse_area_id(area)
url = 'https://trade.jd.com/api/v1/batch/stock'
headers = {
'User-Agent': USER_AGENT,
'Origin': 'https://trade.jd.com',
'Content-Type': 'application/json; charset=UTF-8',
'Referer': 'https://trade.jd.com/shopping/order/getOrderInfo.action?rid=' + str(int(time.time() * 1000)),
}
data = {
"areaRequest": {
"provinceId": area_code[0],
"cityId": area_code[1],
"countyId": area_code[2],
"townId": area_code[3]
},
"skuNumList": []
}
for sku_id in sku_ids:
data['skuNumList'].append({
"skuId": sku_id,
"num": "1"
})
# convert to string
data = json.dumps(data)
resp = self.sess.post(url=url, headers=headers, data=data)
js = parse_json(resp.text)
result = js.get('result')
stock = True
for sku_id in result:
status = result.get(sku_id).get('status')
if '无货' in status:
stock = False
break
return stock
def if_item_in_stock(self, sku_ids, area):
"""判断商品是否有货
:param sku_ids: 商品id,多个商品的id的中间用英文逗号进行分割
:param area: 地址id
:return: 商品是否有货 True/False
"""
sku_ids = parse_sku_id(sku_ids=sku_ids)
if len(sku_ids) > 1: # 多个商品同时查询库存
return self.get_multi_item_stock(sku_ids=sku_ids, area=area)
# 单个商品查询库存
stock_code = self.get_single_item_stock(sku_ids[0], area)[0] # 库存状态码
return True if stock_code == 33 or stock_code == 40 else False # 现货(33)和可配货(40)均可以下单
def get_item_price(self, sku_id):
"""获取商品价格
:param sku_id: 商品id
:return: 价格
"""
url = 'http://p.3.cn/prices/mgets'
payload = {
'type': 1,
'pduid': int(time.time() * 1000),
'skuIds': 'J_' + sku_id,
}
resp = self.sess.get(url=url, params=payload)
js = parse_json(resp.text)
return js['p']
def add_item_to_cart(self, sku_ids):
"""添加商品到购物车
重要:
1.商品添加到购物车后将会自动被勾选✓中。
2.在提交订单时会对勾选的商品进行结算。
3.部分商品(如预售)无法添加到购物车
:param sku_ids: 商品id,格式:"123" 或 "123,456" 或 "123:1,456:2" 或 {"123":1, "456":2}。若不配置数量,默认为1个。
:return:
"""
url = 'https://cart.jd.com/gate.action'
headers = {
'User-Agent': USER_AGENT,
}
# "123" or "123,456" or "123:1,456:2" or {"123":1, "456":2}
if isinstance(sku_ids, str):
if ':' in sku_ids:
sku_ids = parse_sku_id(sku_ids=sku_ids)
else:
sku_ids = {sku_id: 1 for sku_id in parse_sku_id(sku_ids=sku_ids)}
for sku_id, count in sku_ids.items():
payload = {
'pid': sku_id,
'pcount': count,
'ptype': 1,
}
resp = self.sess.get(url=url, params=payload, headers=headers)
soup = BeautifulSoup(resp.text, "html.parser")
tag = soup.select('h3.ftx-02') # [<h3 class="ftx-02">商品已成功加入购物车!</h3>]
if not tag:
print(get_current_time(), '{0}添加到购物车失败'.format(sku_id))
return False
print(get_current_time(), '{0} x {1} 已成功加入购物车'.format(sku_id, count))
def clear_cart(self):
"""清空购物车
包括两个请求:
1.选中购物车中所有的商品
2.批量删除
:return: 清空购物车结果 True/False
"""
# 1.select all items 2.batch remove items
select_url = 'https://cart.jd.com/selectAllItem.action'
remove_url = 'https://cart.jd.com/batchRemoveSkusFromCart.action'
data = {
't': 0,
'outSkus': '',
'random': random.random(),
}
try:
select_resp = self.sess.post(url=select_url, data=data)
remove_resp = self.sess.post(url=remove_url, data=data)
if (not response_status(select_resp)) or (not response_status(remove_resp)):
print(get_current_time(), '购物车清空失败')
return False
print(get_current_time(), '购物车清空成功')
return True
except Exception as e:
print(get_current_time(), e)
return False
def get_cart_detail(self):
"""获取购物车商品详情
:return:
"""
url = 'https://cart.jd.com/cart.action'
cart_detail_format = '商品名称:{0}----单价:{1}----数量:{2}----总价:{3}'
try:
resp = self.sess.get(url=url)
if not response_status(resp):
print(get_current_time(), '获取购物车信息失败')
return
soup = BeautifulSoup(resp.text, "html.parser")
print('************************购物车商品详情************************')
for item in soup.select('div.item-form'):
name = get_tag_value(item.select('div.p-name a'))
price = get_tag_value(item.select('div.p-price strong'))
quantity = get_tag_value(item.select('div.quantity-form input'), 'value')
total_price = get_tag_value(item.select('div.p-sum strong'))
print(cart_detail_format.format(name, price, quantity, total_price))
except Exception as e:
print(get_current_time(), e)
def get_checkout_page_detail(self):
"""访问订单结算页面
该方法会打印出订单结算页面的详细信息:商品名称、价格、数量、库存状态等。
如果只是想下单商品,可以不调用该方法。
:return:
"""
url = 'http://trade.jd.com/shopping/order/getOrderInfo.action'
# url = 'https://cart.jd.com/gotoOrder.action'
payload = {
'rid': str(int(time.time() * 1000)),
}
try:
resp = self.sess.get(url=url, params=payload)
if not response_status(resp):
print(get_current_time(), '获取订单结算页信息失败')
return
soup = BeautifulSoup(resp.text, "html.parser")
self.risk_control = get_tag_value(soup.select('input#riskControl'), 'value')
print('************************订单结算页详情************************')
items = soup.select('div.goods-list div.goods-items')[1:]
checkout_item_detail = '商品名称:{0}----单价:{1}----数量:{2}----库存状态:{3}'
for item in items:
name = get_tag_value(item.select('div.p-name a'))
div_tag = item.select('div.p-price')[0]
price = get_tag_value(div_tag.select('strong.jd-price'))[2:] # remove '¥ ' from the begin of price
quantity = get_tag_value(div_tag.select('span.p-num'))[1:] # remove 'x' from the begin of quantity
state = get_tag_value(div_tag.select('span.p-state')) # in stock or out of stock
print(checkout_item_detail.format(name, price, quantity, state))
sum_price = soup.find('span', id='sumPayPriceId').text[1:] # remove '¥' from the begin of sum price
address = soup.find('span', id='sendAddr').text[5:] # remove '收件人:' from the begin of receiver
receiver = soup.find('span', id='sendMobile').text[4:] # remove '寄送至: ' from the begin of address
print('应付总额:{0}'.format(sum_price))
print('收货地址:{0}----收件人:{1}'.format(address, receiver))
except Exception as e:
print(get_current_time(), e)
def _save_invoice(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': USER_AGENT,
'Referer': 'https://trade.jd.com/shopping/dynamic/invoice/saveInvoice.action',
}
self.sess.post(url=url, data=data, headers=headers)
def submit_order(self):
"""提交订单
重要:
1.该方法只适用于普通商品的提交订单(即可以加入购物车,然后结算提交订单的商品)
2.提交订单时,会对购物车中勾选✓的商品进行结算(如果勾选了多个商品,将会提交成一个订单)
:return: True/False 订单提交结果
"""
if not self.is_login:
print(get_current_time(), '请先登录再提交订单!')
return 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, # Todo: need to get trackId
'submitOrderParam.eid': self.eid,
'submitOrderParam.fp': self.fp,
'submitOrderParam.needCheck': 1,
}
# add payment password when necessary
payment_pwd = global_config.get('account', 'payment_pwd')
if payment_pwd:
data['submitOrderParam.payPassword'] = encrypt_payment_pwd(payment_pwd)
headers = {
'User-Agent': USER_AGENT,
'Host': 'trade.jd.com',
'Referer': 'http://trade.jd.com/shopping/order/getOrderInfo.action',
}
try:
resp = self.sess.post(url=url, data=data, headers=headers)
js = 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 js.get('success'):
print(get_current_time(), '订单提交成功! 订单号:{0}'.format(js.get('orderId')))
return True
else:
message, result_code = js.get('message'), js.get('resultCode')
if result_code == 0:
self._save_invoice()
message = message + '(下单商品可能为第三方商品,将切换为普通发票进行尝试)'
elif result_code == 60077:
message = message + '(可能是购物车为空 或 未勾选购物车中商品)'
elif result_code == 60123:
message = message + '(需要在config.ini文件中配置支付密码)'
print(get_current_time(), '订单提交失败, 错误码:{0}, 返回信息:{1}'.format(result_code, message))
print(get_current_time(), js)
return False
except Exception as e:
print(get_current_time(), e)
return False
def submit_order_by_time(self, buy_time, retry=4, interval=5):
"""定时提交商品订单
重要:该方法只适用于普通商品的提交订单,事先需要先将商品加入购物车并勾选✓。
:param buy_time: 下单时间,例如:'2018-09-28 22:45:50.000'
:param retry: 下单重复执行次数,可选参数,默认4次
:param interval: 下单执行间隔,可选参数,默认5秒
:return:
"""
if not self.is_login:
print(get_current_time(), '请先登录再定时下单!')
return
t = Timer(buy_time=buy_time)
t.start()
for count in range(1, retry + 1):
print(get_current_time(), '第[{0}/{1}]次尝试提交订单……'.format(count, retry))
if self.submit_order():
break
print(get_current_time(), '休息{0}s……'.format(interval))
time.sleep(interval)
else:
print(get_current_time(), '执行结束,提交订单失败!')
def submit_order_by_stock(self, sku_ids, area, interval=3):
"""当商品有库存时提交订单
重要:该方法只适用于普通商品的提交订单,事先需要先将商品加入购物车并勾选✓。
该方法会按照指定的间隔查询库存,当有货时提交订单。
:param sku_ids: 商品id,多个商品id用逗号进行分割,如"123,456,789"
:param area: 地区id
:param interval: 查询库存间隔,可选参数,默认为3秒/次
:return:
"""
while True:
if self.if_item_in_stock(sku_ids=sku_ids, area=area):
print(get_current_time(), '【%s】有货了,正在提交订单……' % sku_ids)
if self.submit_order():
break
else:
print(get_current_time(), '【%s】无货,准备下一次查询' % sku_ids)
time.sleep(interval)
def get_order_info(self, unpaid=True):
"""查询订单信息
:param unpaid: 只显示未付款订单,可选参数,默认为True
:return:
"""
if not self.is_login:
print(get_current_time(), '请先登录再查询订单!')
return False
url = 'https://order.jd.com/center/list.action'
payload = {
'search': 0,
'd': 1,
's': 4096,
} # Orders for nearly three months
headers = {
'User-Agent': USER_AGENT,
'Referer': 'https://passport.jd.com/uc/login?ltype=logout',
}
try:
resp = self.sess.get(url=url, params=payload, headers=headers)
if not response_status(resp):
print(get_current_time(), '获取订单页信息失败')
return
soup = BeautifulSoup(resp.text, "html.parser")
print('************************订单列表页查询************************')
order_table = soup.find('table', {'class': 'order-tb'})
table_bodies = order_table.select('tbody')
exist_order = False
for table_body in table_bodies:
# get order status
order_status = get_tag_value(table_body.select('span.order-status')).replace("订单状态:", "")
# check if order is waiting for payment
# wait_payment = bool(table_body.select('a.btn-pay'))
wait_payment = True if "等待付款" in order_status else False
# only show unpaid orders if unpaid=True
if unpaid and (not wait_payment):
continue
exist_order = True
# get order_time, order_id
tr_th = table_body.select('tr.tr-th')[0]
order_time = get_tag_value(tr_th.select('span.dealtime'))
order_id = get_tag_value(tr_th.select('span.number a'))
# get sum_price, pay_method
sum_price = ''
pay_method = ''
amount_div = table_body.find('div', {'class': 'amount'})
if amount_div:
spans = amount_div.select('span')
pay_method = get_tag_value(spans, index=1)
# if the order is waiting for payment, the price after the discount is shown.
sum_price = get_tag_value(amount_div.select('strong'), index=1)[1:] if wait_payment \
else get_tag_value(spans, index=0)[4:]
# get name and quantity of items in order
items_dict = dict() # {'item_id_1': quantity_1, 'item_id_2': quantity_2, ...}
tr_bds = table_body.select('tr.tr-bd')
for tr_bd in tr_bds:
item = tr_bd.find('div', {'class': 'goods-item'})
if not item:
break
item_id = item.get('class')[1][2:]
quantity = get_tag_value(tr_bd.select('div.goods-number'))[1:]
items_dict[item_id] = quantity
order_info_format = '下单时间:{0}----订单号:{1}----商品列表:{2}----订单状态:{3}----总金额:{4}元----付款方式:{5}'
print(order_info_format.format(order_time, order_id, parse_items_dict(items_dict), order_status,
sum_price, pay_method))
if not exist_order:
print(get_current_time(), '订单查询为空')
except Exception as e:
print(get_current_time(), e)
def _get_seckill_url(self, sku_id):
"""获取商品的抢购链接
点击"抢购"按钮后,会有两次302跳转,最后到达订单结算页面
这里返回第一次跳转后的页面url,作为商品的抢购链接
:param sku_id: 商品id
:return: 商品的抢购链接
"""
url = 'https://itemko.jd.com/itemShowBtn'
payload = {
'callback': 'jQuery{}'.format(random.randint(1000000, 9999999)),
'skuId': sku_id,
'from': 'pc',
'_': str(int(time.time() * 1000)),
}
headers = {
'User-Agent': USER_AGENT,
'Host': 'itemko.jd.com',
'Referer': 'https://item.jd.com/{}.html'.format(sku_id),
}
while True:
resp = self.sess.get(url=url, headers=headers, params=payload)
js = parse_json(resp.text)
if js.get('url'):
# https://divide.jd.com/user_routing?skuId=8654289&sn=c3f4ececd8461f0e4d7267e96a91e0e0&from=pc
router_url = 'https:' + js.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')
print(get_current_time(), "抢购链接获取成功: {0}".format(seckill_url))
return seckill_url
else:
print(get_current_time(), "抢购链接获取失败,{0}不是抢购商品或抢购页面暂未刷新,1秒后重试".format(sku_id))
time.sleep(1)
def request_seckill_url(self, sku_id):
"""访问商品的抢购链接(用于设置cookie等)
:param sku_id: 商品id
:return:
"""
if not self.seckill_url.get(sku_id):
self.seckill_url[sku_id] = self._get_seckill_url(sku_id)
headers = {
'User-Agent': USER_AGENT,
'Host': 'marathon.jd.com',
'Referer': 'https://item.jd.com/{}.html'.format(sku_id),
}
self.sess.get(url=self.seckill_url.get(sku_id), headers=headers, allow_redirects=False)
def request_seckill_checkout_page(self, sku_id, num=1):
"""访问抢购订单结算页面
:param sku_id: 商品id
:param num: 购买数量,可选参数,默认1个
:return:
"""
url = 'https://marathon.jd.com/seckill/seckill.action'
payload = {
'skuId': sku_id,
'num': num,
'rid': int(time.time())
}
headers = {
'User-Agent': USER_AGENT,
'Host': 'marathon.jd.com',
'Referer': 'https://item.jd.com/{}.html'.format(sku_id),
}
self.sess.get(url=url, params=payload, headers=headers)
def _get_seckill_init_info(self, sku_id, num=1):
"""获取秒杀初始化信息(包括:地址,发票,token)
:param sku_id:
:param num: 购买数量,可选参数,默认1个
:return: 初始化信息组成的dict
"""
url = 'https://marathon.jd.com/seckillnew/orderService/pc/init.action'
data = {
'sku': sku_id,
'num': num,
'isModifyAddress': 'false',
}
headers = {
'User-Agent': USER_AGENT,
'Host': 'marathon.jd.com',
}
resp = self.sess.post(url=url, data=data, headers=headers)
return parse_json(resp.text)
def _gen_seckill_order_data(self, sku_id, num=1):
"""生成提交抢购订单所需的请求体参数
:param sku_id: 商品id
:param num: 购买数量,可选参数,默认1个
:return: 请求体参数组成的dict
"""
# 获取用户秒杀初始化信息
if not self.seckill_init_info.get(sku_id):
self.seckill_init_info[sku_id] = self._get_seckill_init_info(sku_id)
init_info = self.seckill_init_info.get(sku_id)
default_address = init_info['addressList'][0] # 默认地址dict
invoice_info = init_info.get('invoiceInfo', {}) # 默认发票信息dict, 有可能不返回
token = init_info['token']
data = {
'skuId': sku_id,
'num': num,
'addressId': default_address['id'],
'yuShou': 'false',
'isModifyAddress': 'false',
'name': default_address['name'],
'provinceId': default_address['provinceId'],
'cityId': default_address['cityId'],
'countyId': default_address['countyId'],