forked from oldcai/51dingpiao
-
Notifications
You must be signed in to change notification settings - Fork 0
/
py12306.py
1386 lines (1281 loc) · 54 KB
/
py12306.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 argparse
import urllib
import time
import datetime
import sys
import re
import ConfigParser
import random
import smtplib
from email.mime.text import MIMEText
import requests
from huzhifeng import dumpObj, hasKeys
# Global variables
RET_OK = 0
RET_ERR = -1
MAX_TRIES = 3
MAX_DAYS = 20
stations = []
seatTypeCodes = [
('1', u'硬座'), # 硬座/无座
('3', u'硬卧'),
('4', u'软卧'),
('7', u'一等软座'),
('8', u'二等软座'),
('9', u'商务座'),
('M', u'一等座'),
('O', u'二等座'),
('B', u'混编硬座'),
('P', u'特等座')
]
cardTypeCodes = [
('1', u'二代身份证'),
('2', u'一代身份证'),
('C', u'港澳通行证'),
('G', u'台湾通行证'),
('B', u'护照')
]
# Set default encoding to utf-8
reload(sys)
sys.setdefaultencoding('utf-8')
requests.packages.urllib3.disable_warnings()
def printDelimiter():
print('-' * 64)
# ------------------------------------------------------------------------------
# Convert station object by name or abbr or pinyin
def getStationByName(name):
matched_stations = []
for station in stations:
if (
station['name'] == name
or station['abbr'].find(name.lower()) != -1
or station['pinyin'].find(name.lower()) != -1
or station['pyabbr'].find(name.lower()) != -1):
matched_stations.append(station)
count = len(matched_stations)
if not count:
return None
elif count == 1:
return matched_stations[0]
else:
for i in xrange(0, count):
print(u'%d:\t%s' % (i + 1, matched_stations[i]['name']))
print(u'请选择站点(1~%d)' % (count))
index = raw_input()
if not index.isdigit():
print(u'只能输入数字序号(1~%d)' % (count))
return None
index = int(index)
if index < 1 or index > count:
print(u'输入的序号无效(1~%d)' % (count))
return None
else:
return matched_stations[index - 1]
# ------------------------------------------------------------------------------
# Get current time with format 2014-01-01 12:00:00
def getTime():
return time.strftime('%Y-%m-%d %X', time.localtime())
# ------------------------------------------------------------------------------
# Get current date with format 2014-01-01
def getDate():
return time.strftime('%Y-%m-%d', time.localtime())
# Convert '2014-01-01' to 'Wed Jan 01 00:00:00 UTC+0800 2014'
def trainDate(d):
t = time.strptime(d, '%Y-%m-%d')
asc = time.asctime(t) # 'Wed Jan 01 00:00:00 2014'
# 'Wed Jan 01 00:00:00 UTC+0800 2014'
return (asc[0:-4] + 'UTC+0800 ' + asc[-4:])
# ------------------------------------------------------------------------------
# 证件类型
def getCardType(cardtype):
d = dict(cardTypeCodes)
if cardtype in d:
return d[cardtype]
else:
return u'未知证件类型'
# ------------------------------------------------------------------------------
# 席别:
def getSeatType(seattype):
d = dict(seatTypeCodes)
if seattype in d:
return d[seattype]
else:
return u'未知席别'
def selectSeatType():
seattype = '1' # 默认硬座
while True:
print(u'请选择席别(注意大小写):')
for xb in seatTypeCodes:
print(u'%s:%s' % (xb[0], xb[1]))
seattype = raw_input()
d = dict(seatTypeCodes)
if seattype in d:
return seattype
else:
print(u'无效的席别类型!')
# ------------------------------------------------------------------------------
# 票种类型
def getTicketType(tickettype):
d = {
'1': u'成人票',
'2': u'儿童票',
'3': u'学生票',
'4': u'残军票'
}
if tickettype in d:
return d[tickettype]
else:
return u'未知票种'
# ------------------------------------------------------------------------------
# Check date format
def checkDate(date):
m = re.match(r'^\d{4}-\d{2}-\d{2}$', date) # 2014-01-01
if m:
today = datetime.datetime.now()
fmt = '%Y-%m-%d'
today = datetime.datetime.strptime(today.strftime(fmt), fmt)
train_date = datetime.datetime.strptime(m.group(0), fmt)
delta = train_date - today
if delta.days < 0:
print(u'乘车日期%s无效, 只能预订%s以后的车票' % (
train_date.strftime(fmt),
today.strftime(fmt)))
return 0
else:
return 1
else:
return 0
# ------------------------------------------------------------------------------
# Input date
def inputDate(prompt=''):
train_date = ''
index = 0
week_days = [u'星期一', u'星期二', u'星期三', u'星期四', u'星期五', u'星期六', u'星期天']
now = datetime.datetime.now()
available_date = [(now + datetime.timedelta(days=i)) for i in xrange(MAX_DAYS)]
for i in xrange(MAX_DAYS):
print(u'%2d: %04d-%02d-%02d(%s)' % (
i, available_date[i].year, available_date[i].month,
available_date[i].day, week_days[available_date[i].weekday()]))
while True:
print(u'%s(请选择乘车日期0~%d)' % (prompt, (MAX_DAYS - 1)))
index = raw_input()
if not index.isdigit():
print(u'只能输入数字序号,请重新选择乘车日期(0~%d)' % (MAX_DAYS - 1))
continue
index = int(index)
if index < 0 or index >= MAX_DAYS:
print(u'输入的序号无效,请重新选择乘车日期(0~%d)' % (MAX_DAYS - 1))
continue
train_date = '%04d-%02d-%02d' % (
available_date[index].year,
available_date[index].month,
available_date[index].day)
if checkDate(train_date):
break
return train_date
# ------------------------------------------------------------------------------
# Input station
def inputStation(prompt=''):
station = None
print(u'%s (支持中文,拼音和拼音缩写,如:北京,beijing,bj)' % (prompt))
while True:
name = raw_input().decode('gb2312', 'ignore')
station = getStationByName(name)
if station:
return station
else:
print(u'站点错误,没有站点"%s",请重新输入:' % (name))
def selectTrain(trains):
trains_num = len(trains)
index = 0
while True: # 必须选择有效的车次
index = raw_input()
if not index.isdigit():
print(u'只能输入数字序号,请重新选择车次(1~%d)' % (trains_num))
continue
index = int(index)
if index < 1 or index > trains_num:
print(u'输入的序号无效,请重新选择车次(1~%d)' % (trains_num))
continue
if trains[index - 1]['queryLeftNewDTO']['canWebBuy'] != 'Y':
print(u'您选择的车次%s没票啦,请重新选择车次' % (
trains[index - 1]['queryLeftNewDTO']['station_train_code']))
continue
else:
break
return index
class MyOrder(object):
'''docstring for MyOrder'''
def __init__(
self,
username='',
password='',
train_date='',
from_city_name='',
to_city_name=''):
super(MyOrder, self).__init__()
self.username = username # 账号
self.password = password # 密码
self.train_date = train_date # 乘车日期[2014-01-01]
self.back_train_date = getDate() # 返程日期[2014-01-01]
self.tour_flag = 'dc' # 单程dc/往返wf
self.purpose_code = 'ADULT' # 成人票
self.from_city_name = from_city_name # 对应查询界面'出发地'输入框中的内容
self.to_city_name = to_city_name # 对应查询界面'目的地'输入框中的内容
self.from_station_telecode = '' # 出发站编码
self.to_station_telecode = '' # 目的站编码
self.passengers = [] # 乘车人列表,最多5人
self.normal_passengers = [] # 我的联系人列表
self.trains = [] # 列车列表, 查询余票后自动更新
self.current_train_index = 0 # 当前选中的列车索引序号
self.captcha = '' # 图片验证码
self.orderId = '' # 订单流水号
self.notify = {
'mail_enable': 0,
'mail_username': '',
'mail_password': '',
'mail_server': '',
'mail_to': [],
'dates': [],
'trains': [],
'xb': [],
'focus': {}
}
def initSession(self):
self.session = requests.Session()
self.session.headers = {
'Accept': 'image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*',
'Accept-Encoding': 'deflate',
'Accept-Language': 'zh-CN',
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E; MALC)',
'Referer': 'https://kyfw.12306.cn/otn/index/init',
'Host': 'kyfw.12306.cn',
'Connection': 'Keep-Alive'
}
def get(self, url):
self.session.headers.update({'Content-Type': None})
tries = 0
while tries < MAX_TRIES:
tries += 1
try:
r = self.session.get(url, verify=False, timeout=16)
except requests.exceptions.ConnectionError as e:
print('ConnectionError(%s): e=%s' % (url, e))
except requests.exceptions.Timeout as e:
print('Timeout(%s): e=%s' % (url, e))
except requests.exceptions.TooManyRedirects as e:
print('TooManyRedirects(%s): e=%s' % (url, e))
except requests.exceptions.HTTPError as e:
print('HTTPError(%s): e=%s' % (url, e))
except requests.exceptions.RequestException as e:
print('RequestException(%s): e=%s' % (url, e))
except:
print('Unknown exception(%s)' % (url))
if r.status_code != 200:
print('Request %s failed %d times, status_code=%d' % (
url,
tries,
r.status_code))
else:
return r
else:
return None
def post(self, url, payload):
self.session.headers.update({'Content-Type': 'application/x-www-form-urlencoded'})
tries = 0
while tries < MAX_TRIES:
tries += 1
try:
r = self.session.post(url, data=payload, verify=False, timeout=16)
except requests.exceptions.ConnectionError as e:
print('ConnectionError(%s): e=%s' % (url, e))
except requests.exceptions.Timeout as e:
print('Timeout(%s): e=%s' % (url, e))
except requests.exceptions.TooManyRedirects as e:
print('TooManyRedirects(%s): e=%s' % (url, e))
except requests.exceptions.HTTPError as e:
print('HTTPError(%s): e=%s' % (url, e))
except requests.exceptions.RequestException as e:
print('RequestException(%s): e=%s' % (url, e))
except:
print('Unknown exception(%s)' % (url))
if r.status_code != 200:
print('Request %s failed %d times, status_code=%d' % (
url,
tries,
r.status_code))
else:
return r
else:
return None
def getCaptcha(self, url, module, rand):
rand_url = 'https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew.do?module=%s&rand=%s' % (module, rand)
captcha = ''
while True:
r = self.session.get(url, verify=False, stream=True, timeout=16)
with open('captcha.gif', 'wb') as fd:
for chunk in r.iter_content():
fd.write(chunk)
print(u'请输入4位图片验证码(直接回车刷新):')
url = '%s&%1.16f' % (rand_url, random.random())
captcha = raw_input()
if len(captcha) == 4:
return captcha
# ------------------------------------------------------------------------------
# 火车站点数据库初始化
# 全部站点, 数据来自: https://kyfw.12306.cn/otn/resources/js/framework/station_name.js
# 每个站的格式如下:
# @bji|北京|BJP|beijing|bj|2 ---> @拼音缩写三位|站点名称|编码|拼音|拼音缩写|序号
def initStation(self):
url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js'
referer = 'https://kyfw.12306.cn/otn/'
self.session.headers.update({'Referer': referer})
r = self.get(url)
if not r:
print(u'站点数据库初始化失败, 请求异常')
return None
data = r.text
station_list = data.split('@')
if len(station_list) < 1:
print(u'站点数据库初始化失败, 数据异常')
return None
station_list = station_list[1:]
for station in station_list:
items = station.split('|') # bjb|北京北|VAP|beijingbei|bjb|0
if len(items) < 5:
print(u'忽略无效站点: %s' % (items))
continue
stations.append({'abbr': items[0],
'name': items[1],
'telecode': items[2],
'pinyin': items[3],
'pyabbr': items[4]})
return stations
def readConfig(self, config_file='config.ini'):
cp = ConfigParser.ConfigParser()
try:
cp.readfp(open(config_file, 'r'))
except IOError as e:
print(u'打开配置文件"%s"失败啦, 请先创建或者拷贝一份配置文件config.ini' % (config_file))
if raw_input('Press any key to continue'):
sys.exit()
self.username = cp.get('login', 'username')
self.password = cp.get('login', 'password')
self.train_date = cp.get('train', 'date')
self.from_city_name = cp.get('train', 'from')
self.to_city_name = cp.get('train', 'to')
self.notify['mail_enable'] = int(cp.get('notify', 'mail_enable'))
self.notify['mail_username'] = cp.get('notify', 'mail_username')
self.notify['mail_password'] = cp.get('notify', 'mail_password')
self.notify['mail_server'] = cp.get('notify', 'mail_server')
self.notify['mail_to'] = cp.get('notify', 'mail_to').split(',')
self.notify['dates'] = cp.get('notify', 'dates').split(',')
self.notify['trains'] = cp.get('notify', 'trains').split(',')
self.notify['xb'] = cp.get('notify', 'xb').split(',')
for t in self.notify['trains']:
self.notify['focus'][t] = self.notify['xb']
# 检查出发站
station = getStationByName(self.from_city_name)
if not station:
station = inputStation(u'出发站错误,请重新输入:')
self.from_city_name = station['name']
self.from_station_telecode = station['telecode']
# 检查目的站
station = getStationByName(self.to_city_name)
if not station:
station = inputStation(u'目的站错误,请重新输入:')
self.to_city_name = station['name']
self.to_station_telecode = station['telecode']
# 检查乘车日期
if not checkDate(self.train_date):
self.train_date = inputDate(u'乘车日期错误,请重新输入:')
# 分析乘客信息
self.passengers = []
index = 1
passenger_sections = ['passenger%d' % (i) for i in xrange(1, 6)]
sections = cp.sections()
for section in passenger_sections:
if section in sections:
passenger = {}
passenger['index'] = index
passenger['name'] = cp.get(section, 'name') # 必选参数
passenger['cardtype'] = cp.get(
section,
'cardtype') if cp.has_option(
section,
'cardtype') else '1' # 证件类型:可选参数,默认值1,即二代身份证
passenger['id'] = cp.get(section, 'id') # 必选参数
passenger['phone'] = cp.get(
section,
'phone') if cp.has_option(
section,
'phone') else '13800138000' # 手机号码
passenger['seattype'] = cp.get(
section,
'seattype') if cp.has_option(
section,
'seattype') else '1' # 席别:可选参数, 默认值1, 即硬座
passenger['tickettype'] = cp.get(
section,
'tickettype') if cp.has_option(
section,
'tickettype') else '1' # 票种:可选参数, 默认值1, 即成人票
self.passengers.append(passenger)
index += 1
def printConfig(self):
printDelimiter()
print(u'订票信息:\n%s\t%s\t%s--->%s' % (
self.username,
self.train_date,
self.from_city_name,
self.to_city_name))
printDelimiter()
th = [u'序号', u'姓名', u'证件类型', u'证件号码', u'席别', u'票种']
print(u'%s\t%s\t%s\t%s\t%s\t%s' % (
th[0].ljust(2), th[1].ljust(4), th[2].ljust(5),
th[3].ljust(12), th[4].ljust(2), th[5].ljust(3)))
for p in self.passengers:
print(u'%s\t%s\t%s\t%s\t%s\t%s' % (
p['index'],
p['name'].decode('utf-8', 'ignore').ljust(4),
getCardType(p['cardtype']).ljust(5),
p['id'].ljust(20),
getSeatType(p['seattype']).ljust(2),
getTicketType(p['tickettype']).ljust(3)))
def login(self):
url = 'https://kyfw.12306.cn/otn/login/init'
referer = 'https://kyfw.12306.cn/otn/'
self.session.headers.update({'Referer': referer})
r = self.get(url)
if not r:
print(u'登录失败, 请求异常')
return RET_ERR
if self.session.cookies:
cookies = requests.utils.dict_from_cookiejar(self.session.cookies)
if cookies['JSESSIONID']:
self.jsessionid = cookies['JSESSIONID']
tries = 0
referer = 'https://kyfw.12306.cn/otn/login/init'
self.session.headers.update({'Referer': referer})
while tries < MAX_TRIES:
tries += 1
print(u'接收登录验证码...')
url = 'https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=login&rand=sjrand'
self.captcha = self.getCaptcha(url, 'login', 'sjrand')
print(u'正在校验登录验证码...')
url = 'https://kyfw.12306.cn/otn/passcodeNew/checkRandCodeAnsyn'
parameters = [
('randCode', self.captcha),
('rand', 'sjrand'),
]
payload = urllib.urlencode(parameters)
r = self.post(url, payload)
if not r:
print(u'登录失败, 校验登录验证码异常')
continue
# {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"result":"1","msg":"randCodeRight"},"messages":[],"validateMessages":{}}
# {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"result":"0","msg":"randCodeError"},"messages":[],"validateMessages":{}}
obj = r.json()
if (
hasKeys(obj, ['status', 'httpstatus', 'data'])
and hasKeys(obj['data'], ['result', 'msg'])
and (obj['data']['result'] == '1')):
print(u'校验登录验证码成功')
break
else:
print(u'校验登录验证码失败')
dumpObj(obj)
continue
else:
print(u'尝试次数太多,自动退出程序以防账号被冻结')
sys.exit()
print(u'正在登录...')
url = 'https://kyfw.12306.cn/otn/login/loginAysnSuggest'
referer = 'https://kyfw.12306.cn/otn/login/init'
self.session.headers.update({'Referer': referer})
parameters = [
('loginUserDTO.user_name', self.username),
('userDTO.password', self.password),
('randCode', self.captcha),
]
payload = urllib.urlencode(parameters)
r = self.post(url, payload)
if not r:
print(u'登录失败, 请求异常')
return RET_ERR
# {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"loginCheck":"Y"},"messages":[],"validateMessages":{}}
obj = r.json()
if (
hasKeys(obj, ['status', 'httpstatus', 'data'])
and hasKeys(obj['data'], ['loginCheck'])
and (obj['data']['loginCheck'] == 'Y')):
print(u'登陆成功^_^')
return RET_OK
else:
print(u'登陆失败啦!重新登陆...')
dumpObj(obj)
return RET_ERR
def loginProc(self):
tries = 0
while tries < MAX_TRIES:
tries += 1
printDelimiter()
if self.login() == RET_OK:
break
else:
print(u'失败次数太多,自动退出程序')
sys.exit()
def getPassengerDTOs(self):
url = 'https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs'
referer = 'https://kyfw.12306.cn/otn/leftTicket/init'
self.session.headers.update({'Referer': referer})
parameters = [
('', ''),
]
payload = urllib.urlencode(parameters)
r = self.post(url, payload)
if not r:
print(u'获取乘客信息异常')
return RET_ERR
obj = r.json()
if (
hasKeys(obj, ['status', 'httpstatus', 'data'])
and hasKeys(obj['data'], ['normal_passengers'])
and len(obj['data']['normal_passengers'])):
self.normal_passengers = obj['data']['normal_passengers']
return RET_OK
else:
print(u'获取乘客信息失败')
if hasKeys(obj, ['messages']):
dumpObj(obj['messages'])
if hasKeys(obj, ['data']) and hasKeys(obj['data'], ['exMsg']):
dumpObj(obj['data']['exMsg'])
return RET_ERR
def selectPassengers(self, prompt):
if prompt == 1:
print(u'是否选择乘客?(如需选择请输入y或者yes, 默认不做选择, 使用配置文件提供的乘客信息)')
act = raw_input()
act = act.lower()
if act != 'y' and act != 'yes':
return RET_OK
if not (self.normal_passengers and len(self.normal_passengers)):
tries = 0
while tries < MAX_TRIES:
tries += 1
if self.getPassengerDTOs() == RET_OK:
break
else:
print(u'获取乘客信息失败次数太多')
return RET_ERR
num = len(self.normal_passengers)
for i in xrange(0, num):
p = self.normal_passengers[i]
print(u'%d.%s \t' % (i + 1, p['passenger_name'])),
if (i + 1) % 5 == 0:
print('')
while True:
print(u'\n请选择乘车人, 最多选择5个, 以逗号隔开, 如:1,2,3,4,5, 直接回车不选择, 使用配置文件中的乘客信息')
buf = raw_input()
if not buf:
return RET_ERR
pattern = re.compile(r'^[0-9,]*\d$') # 只能输入数字和逗号, 并且必须以数字结束
if pattern.match(buf):
break
else:
print(u'输入格式错误, 只能输入数字和逗号, 并且必须以数字结束, 如:1,2,3,4,5')
ids = buf.split(',')
if not (ids and 1 <= len(ids) <= 5):
return RET_ERR
seattype = selectSeatType()
ids = [int(id) for id in ids]
del self.passengers[:]
for id in ids:
if id < 1 or id > num:
print(u'不存在的联系人, 忽略')
else:
passenger = {}
id = id - 1
passenger['index'] = len(self.passengers) + 1
passenger['name'] = self.normal_passengers[id]['passenger_name']
passenger['cardtype'] = self.normal_passengers[id]['passenger_id_type_code']
passenger['id'] = self.normal_passengers[id]['passenger_id_no']
passenger['phone'] = self.normal_passengers[id]['mobile_no']
passenger['seattype'] = seattype
passenger['tickettype'] = self.normal_passengers[id]['passenger_type']
self.passengers.append(passenger)
self.printConfig()
return RET_OK
def queryTickets(self):
url = 'https://kyfw.12306.cn/otn/leftTicket/query?'
referer = 'https://kyfw.12306.cn/otn/leftTicket/init'
self.session.headers.update({'Referer': referer})
parameters = [
('leftTicketDTO.train_date', self.train_date),
('leftTicketDTO.from_station', self.from_station_telecode),
('leftTicketDTO.to_station', self.to_station_telecode),
('purpose_codes', self.purpose_code),
]
url += urllib.urlencode(parameters)
r = self.get(url)
if not r:
print(u'查询车票异常')
return RET_ERR
obj = r.json()
if (hasKeys(obj, ['status', 'httpstatus', 'data']) and len(obj['data'])):
self.trains = obj['data']
return RET_OK
else:
print(u'查询车票失败')
if hasKeys(obj, ['messages']):
dumpObj(obj['messages'])
return RET_ERR
def sendMailNotification(self):
print(u'正在发送邮件提醒...')
me = u'订票提醒<%s>' % (self.notify['mail_username'])
msg = MIMEText(
self.notify['mail_content'],
_subtype='plain',
_charset='gb2312')
msg['Subject'] = u'余票信息'
msg['From'] = me
msg['To'] = ';'.join(self.notify['mail_to'])
try:
server = smtplib.SMTP()
server.connect(self.notify['mail_server'])
server.login(
self.notify['mail_username'],
self.notify['mail_password'])
server.sendmail(me, self.notify['mail_to'], msg.as_string())
server.close()
print(u'发送邮件提醒成功')
return True
except Exception as e:
print(u'发送邮件提醒失败, %s' % str(e))
return False
def printTrains(self):
printDelimiter()
print(u"%s\t%s--->%s '有':票源充足 '无':票已售完 '*':未到起售时间 '--':无此席别" % (
self.train_date,
self.from_city_name,
self.to_city_name))
print(u'余票查询结果如下:')
printDelimiter()
print(u'序号/车次\t乘车站\t目的站\t一等座\t二等座\t软卧\t硬卧\t软座\t硬座\t无座\t价格')
seatTypeCode = {
'swz': '商务座',
'tz': '特等座',
'zy': '一等座',
'ze': '二等座',
'gr': '高级软卧',
'rw': '软卧',
'yw': '硬卧',
'rz': '软座',
'yz': '硬座',
'wz': '无座',
'qt': '其它',
}
printDelimiter()
# TODO 余票数量和票价 https://kyfw.12306.cn/otn/leftTicket/queryTicketPrice?train_no=770000K77505&from_station_no=09&to_station_no=13&seat_types=1431&train_date=2014-01-01
# yp_info=4022300000301440004610078033421007800536 代表
# 4022300000 软卧0
# 3014400046 硬卧46
# 1007803342 无座342
# 1007800536 硬座536
index = 1
self.notify['mail_content'] = ''
for train in self.trains:
t = train['queryLeftNewDTO']
status = '售完' if t['canWebBuy'] == 'N' else '预定'
i = 0
ypInfo = {
'wz': { # 无座
'price': 0,
'left': 0
},
'yz': { # 硬座
'price': 0,
'left': 0
},
'yw': { # 硬卧
'price': 0,
'left': 0
},
'rw': { # 软卧
'price': 0,
'left': 0
},
}
# 分析票价和余票数量
while i < (len(t['yp_info']) / 10):
tmp = t['yp_info'][i * 10:(i + 1) * 10]
price = int(tmp[1:5])
left = int(tmp[-3:])
if tmp[0] == '1':
if tmp[6] == '3':
ypInfo['wz']['price'] = price
ypInfo['wz']['left'] = left
else:
ypInfo['yz']['price'] = price
ypInfo['yz']['left'] = left
elif tmp[0] == '3':
ypInfo['yw']['price'] = price
ypInfo['yw']['left'] = left
elif tmp[0] == '4':
ypInfo['rw']['price'] = price
ypInfo['rw']['left'] = left
i = i + 1
yz_price = u'硬座%s' % (
ypInfo['yz']['price']) if ypInfo['yz']['price'] else ''
yw_price = u'硬卧%s' % (
ypInfo['yw']['price']) if ypInfo['yw']['price'] else ''
print(u'(%d) %s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s%s' % (
index,
t['station_train_code'],
t['from_station_name'],
t['to_station_name'],
t['zy_num'],
t['ze_num'],
ypInfo['rw']['left'] if ypInfo['rw']['left'] else t['rw_num'],
ypInfo['yw']['left'] if ypInfo['yw']['left'] else t['yw_num'],
t['rz_num'],
ypInfo['yz']['left'] if ypInfo['yz']['left'] else t['yz_num'],
ypInfo['wz']['left'] if ypInfo['wz']['left'] else t['wz_num'],
yz_price,
yw_price))
index += 1
if self.notify['mail_enable'] == 1 and t['canWebBuy'] == 'Y':
msg = ''
prefix = u'[%s]车次%s[%s/%s->%s/%s, 历时%s]现在有票啦\n' % (
t['start_train_date'],
t['station_train_code'],
t['from_station_name'],
t['start_time'],
t['to_station_name'],
t['arrive_time'],
t['lishi'])
if 'all' in self.notify['focus']: # 任意车次
if self.notify['focus']['all'][0] == 'all': # 任意席位
msg = prefix
else: # 指定席位
for seat in self.notify['focus']['all']:
if seat in ypInfo and ypInfo[seat]['left']:
msg += u'座位类型:%s, 剩余车票数量:%s, 票价:%s \n' % (
seat if seat not in seatTypeCode else seatTypeCode[seat],
ypInfo[seat]['left'],
ypInfo[seat]['price'])
if msg:
msg = prefix + msg + u'\n'
elif t['station_train_code'] in self.notify['focus']: # 指定车次
# 任意席位
if self.notify['focus'][t['station_train_code']][0] == 'all':
msg = prefix
else: # 指定席位
for seat in self.notify['focus'][t['station_train_code']]:
if seat in ypInfo and ypInfo[seat]['left']:
msg += u'座位类型:%s, 剩余车票数量:%s, 票价:%s \n' % (
seat if seat not in seatTypeCode else seatTypeCode[seat],
ypInfo[seat]['left'],
ypInfo[seat]['price'])
if msg:
msg = prefix + msg + u'\n'
self.notify['mail_content'] += msg
printDelimiter()
if self.notify['mail_enable'] == 1:
if self.notify['mail_content']:
self.sendMailNotification()
return RET_OK
else:
length = len(self.notify['dates'])
if length > 1:
self.train_date = self.notify['dates'][
random.randint(
0,
length -
1)]
return RET_ERR
else:
return RET_OK
# -1->重新查询/0->退出程序/1~len->车次序号
def selectAction(self):
ret = -1
self.current_train_index = 0
trains_num = len(self.trains)
print(u'您可以选择:')
print(u'1~%d.选择车次开始订票' % (trains_num))
print(u'p.更换乘车人')
print(u's.更改席别')
print(u'd.更改乘车日期')
print(u'f.更改出发站')
print(u't.更改目的站')
print(u'a.同时更改乘车日期,出发站和目的站')
print(u'u.查询未完成订单')
print(u'r.刷票模式')
print(u'n.普通模式')
print(u'q.退出')
print(u'刷新车票请直接回车')
printDelimiter()
select = raw_input()
select = select.lower()
if select.isdigit():
index = int(select)
if index < 1 or index > trains_num:
print(u'输入的序号无效,请重新选择车次(1~%d)' % (trains_num))
index = selectTrain(self.trains)
if self.trains[index - 1]['queryLeftNewDTO']['canWebBuy'] != 'Y':
print(u'您选择的车次%s没票啦,请重新选择车次' % (self.trains[index - 1]['queryLeftNewDTO']['station_train_code']))
index = selectTrain(self.trains)
ret = index
self.current_train_index = index - 1
elif select == 'p':
self.selectPassengers(0)
elif select == 's':
seattype = selectSeatType()
for p in self.passengers:
p['seattype'] = seattype
self.printConfig()
elif select == 'd':
self.train_date = inputDate()
elif select == 'f':
station = inputStation(u'请输入出发站:')
self.from_city_name = station['name']
self.from_station_telecode = station['telecode']
elif select == 't':
station = inputStation(u'请输入目的站:')
self.to_city_name = station['name']
self.to_station_telecode = station['telecode']
elif select == 'a':
self.train_date = inputDate()
station = inputStation(u'请输入出发站:')
self.from_city_name = station['name']
self.from_station_telecode = station['telecode']
station = inputStation(u'请输入目的站:')
self.to_city_name = station['name']
self.to_station_telecode = station['telecode']
elif select == 'u':
ret = self.queryMyOrderNotComplete()
ret = self.selectAction()
elif select == 'r':
self.notify['mail_enable'] = 1
ret = -1
elif select == 'n':
self.notify['mail_enable'] = 0
ret = -1
elif select == 'q':
ret = 0
return ret
def initOrder(self):
print(u'准备下单喽')
url = 'https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest'
referer = 'https://kyfw.12306.cn/otn/leftTicket/init'
self.session.headers.update({'Referer': referer})
parameters = [
('secretStr', self.trains[self.current_train_index]['secretStr']),
('train_date', self.train_date),
('back_train_date', self.back_train_date),
('tour_flag', self.tour_flag),
('purpose_codes', self.purpose_code),
('query_from_station_name', self.from_city_name),
('query_to_station_name', self.to_city_name),
('undefined', '')
]
# TODO 注意:此处post不需要做urlencode, 比较奇怪, 不能用urllib.urlencode(parameters)
payload = ''
length = len(parameters)
for i in range(0, length):
payload += parameters[i][0] + '=' + parameters[i][1]
if i < (length - 1):
payload += '&'
r = self.post(url, payload)
if not r:
print(u'下单异常')
return RET_ERR
# {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"messages":[],"validateMessages":{}}
obj = r.json()
if not (hasKeys(obj, ['status', 'httpstatus'])
and obj['status']):
print(u'下单失败啦')
dumpObj(obj)
return RET_ERR
print(u'订单初始化...')
url = 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'
referer = 'https://kyfw.12306.cn/otn/leftTicket/init'
self.session.headers.update({'Referer': referer})
parameters = [
('_json_att', ''),
]
payload = urllib.urlencode(parameters)
r = self.post(url, payload)
if not r:
print(u'订单初始化异常')
return RET_ERR
data = r.text
s = data.find('globalRepeatSubmitToken') # TODO
e = data.find('global_lang')
if s == -1 or e == -1:
print(u'找不到 globalRepeatSubmitToken')