-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpy12306.py
1544 lines (1458 loc) · 59.8 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
from itertools import chain
import json
# 第三方库
import requests
from huzhifeng import dumpObj, hasKeys
# Set default encoding to utf-8
reload(sys)
sys.setdefaultencoding('utf-8')
requests.packages.urllib3.disable_warnings()
# 全局变量
RET_OK = 0
RET_ERR = -1
MAX_TRIES = 3
MAX_DAYS = 60
stations = []
seatMaps = [
('1', u'硬座'), # 硬座/无座
('3', u'硬卧'),
('4', u'软卧'),
('7', u'一等软座'),
('8', u'二等软座'),
('9', u'商务座'),
('M', u'一等座'),
('O', u'二等座'),
('B', u'混编硬座'),
('P', u'特等座')
]
# 全局函数
def printDelimiter():
print('-' * 64)
def getTime():
return time.strftime('%Y-%m-%d %X', time.localtime()) # 2014-01-01 12:00:00
def date2UTC(d):
# Convert '2014-01-01' to 'Wed Jan 01 00:00:00 UTC+0800 2014'
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(key):
d = {
'1': u'二代身份证',
'2': u'一代身份证',
'C': u'港澳通行证',
'G': u'台湾通行证',
'B': u'护照'
}
return d[key] if key in d else u'未知证件类型'
def getTicketType(key):
d = {
'1': u'成人票',
'2': u'儿童票',
'3': u'学生票',
'4': u'残军票'
}
return d[key] if key in d else u'未知票种'
def getSeatType(key):
d = dict(seatMaps)
return d[key] if key in d else u'未知席别'
def selectSeatType():
key = '1' # 默认硬座
while True:
print(u'请选择席别编码(即左边第一个英文字母):')
for xb in seatMaps:
print(u'%s: %s' % (xb[0], xb[1]))
key = raw_input().upper()
d = dict(seatMaps)
if key in d:
return key
else:
print(u'无效的席别类型!')
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 False
else:
return True
else:
return False
def selectDate():
fmt = '%Y-%m-%d'
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(0, MAX_DAYS, 2):
print(u'第%2d天: %s(%s)' % (
i + 1, available_date[i].strftime(fmt), week_days[available_date[i].weekday()])),
if i + 1 < MAX_DAYS:
print(u'\t\t第%2d天: %s(%s)' % (
i + 2, available_date[i + 1].strftime(fmt), week_days[available_date[i + 1].weekday()]))
else:
print('')
while True:
print(u'请选择乘车日期(1~%d)' % (MAX_DAYS))
index = raw_input()
if not index.isdigit():
print(u'只能输入数字序号, 请重新选择乘车日期(1~%d)' % (MAX_DAYS))
continue
index = int(index)
if index < 1 or index > MAX_DAYS:
print(u'输入的序号无效, 请重新选择乘车日期(1~%d)' % (MAX_DAYS))
continue
index -= 1
train_date = available_date[index].strftime(fmt)
return train_date
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 count <= 0:
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]
def inputStation():
while True:
print(u'支持中文, 拼音和拼音缩写(如: 北京,beijing,bj)')
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]
today = datetime.datetime.now()
self.back_train_date = today.strftime('%Y-%m-%d') # 返程日期[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.canWebBuy = False # 可预订
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': 'application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, */*',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN',
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)',
'Referer': 'https://kyfw.12306.cn/otn/index/init',
'Host': 'kyfw.12306.cn',
'Connection': 'Keep-Alive'
}
def updateHeaders(self, url):
d = {
'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js': {
'method': 'GET',
'Referer': 'https://kyfw.12306.cn/otn/'
},
'https://kyfw.12306.cn/otn/login/init': {
'method': 'GET',
'Referer': 'https://kyfw.12306.cn/otn/'
},
'https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=login&rand=sjrand&': {
'method': 'GET',
'Referer': 'https://kyfw.12306.cn/otn/login/init'
},
'https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=passenger&rand=randp&': {
'method': 'GET',
'Referer': 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'
},
'https://kyfw.12306.cn/otn/passcodeNew/checkRandCodeAnsyn': {
'method': 'POST',
'Referer': 'https://kyfw.12306.cn/otn/login/init',
'Cache-Control': 'no-cache',
'x-requested-with': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
'https://kyfw.12306.cn/otn/login/loginAysnSuggest': {
'method': 'POST',
'Referer': 'https://kyfw.12306.cn/otn/login/init',
'Cache-Control': 'no-cache',
'x-requested-with': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
'https://kyfw.12306.cn/otn/login/userLogin': {
'method': 'POST',
'Referer': 'https://kyfw.12306.cn/otn/login/init'
},
'https://kyfw.12306.cn/otn/index/init': {
'method': 'GET',
'Referer': 'https://kyfw.12306.cn/otn/login/init'
},
'https://kyfw.12306.cn/otn/leftTicket/init': {
'method': 'POST',
'Referer': 'https://kyfw.12306.cn/otn/index/init',
'Content-Type': 'application/x-www-form-urlencoded'
},
'https://kyfw.12306.cn/otn/leftTicket/log?': {
'method': 'GET',
'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init',
'x-requested-with': 'XMLHttpRequest',
'Cache-Control': 'no-cache',
'If-Modified-Since': '0'
},
'https://kyfw.12306.cn/otn/leftTicket/query?': {
'method': 'GET',
'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init',
'x-requested-with': 'XMLHttpRequest',
'Cache-Control': 'no-cache',
'If-Modified-Since': '0'
},
'https://kyfw.12306.cn/otn/leftTicket/queryT?': {
'method': 'GET',
'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init',
'x-requested-with': 'XMLHttpRequest',
'Cache-Control': 'no-cache',
'If-Modified-Since': '0'
},
'https://kyfw.12306.cn/otn/login/checkUser': {
'method': 'POST',
'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init',
'Cache-Control': 'no-cache',
'If-Modified-Since': '0',
'x-requested-with': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
'https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest': {
'method': 'POST',
'Referer': 'https://kyfw.12306.cn/otn/',
'Cache-Control': 'no-cache',
'x-requested-with': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
'https://kyfw.12306.cn/otn/confirmPassenger/initDc': {
'method': 'POST',
'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init',
'Content-Type': 'application/x-www-form-urlencoded',
'Cache-Control': 'no-cache'
},
'https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs': {
'method': 'POST',
'Referer': 'https://kyfw.12306.cn/otn/confirmPassenger/initDc',
'Cache-Control': 'no-cache',
'x-requested-with': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
'https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo': {
'method': 'POST',
'Referer': 'https://kyfw.12306.cn/otn/confirmPassenger/initDc',
'Cache-Control': 'no-cache',
'x-requested-with': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
'https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount': {
'method': 'POST',
'Referer': 'https://kyfw.12306.cn/otn/confirmPassenger/initDc',
'Cache-Control': 'no-cache',
'x-requested-with': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
'https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue': {
'method': 'POST',
'Referer': 'https://kyfw.12306.cn/otn/confirmPassenger/initDc',
'Cache-Control': 'no-cache',
'x-requested-with': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
'https://kyfw.12306.cn/otn/confirmPassenger/queryOrderWaitTime?': {
'method': 'GET',
'Referer': 'https://kyfw.12306.cn/otn/confirmPassenger/initDc',
'x-requested-with': 'XMLHttpRequest'
},
'https://kyfw.12306.cn/otn/confirmPassenger/resultOrderForDcQueue': {
'method': 'POST',
'Referer': 'https://kyfw.12306.cn/otn/confirmPassenger/initDc',
'Cache-Control': 'no-cache',
'x-requested-with': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
'https://kyfw.12306.cn/otn//payOrder/init?': {
'method': 'POST',
'Referer': 'https://kyfw.12306.cn/otn/confirmPassenger/initDc',
'Cache-Control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded'
},
'https://kyfw.12306.cn/otn/queryOrder/initNoComplete': {
'method': 'GET',
'Referer': 'https://kyfw.12306.cn/otn//payOrder/init?random=1417862054369'
},
'https://kyfw.12306.cn/otn/queryOrder/queryMyOrderNoComplete': {
'method': 'POST',
'Referer': 'https://kyfw.12306.cn/otn/queryOrder/initNoComplete',
'Cache-Control': 'no-cache',
'x-requested-with': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}
l = [
'https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=login&rand=sjrand&',
'https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=passenger&rand=randp&',
'https://kyfw.12306.cn/otn/leftTicket/log?',
'https://kyfw.12306.cn/otn/leftTicket/query?',
'https://kyfw.12306.cn/otn/leftTicket/queryT?',
'https://kyfw.12306.cn/otn/confirmPassenger/queryOrderWaitTime?',
'https://kyfw.12306.cn/otn//payOrder/init?'
]
for s in l:
if url.find(s) == 0:
url = s
if not url in d:
print(u'未知 url: %s' % url)
return RET_ERR
self.session.headers.update({'Referer': d[url]['Referer']})
keys = [
'Referer',
'Cache-Control',
'x-requested-with',
'Content-Type'
]
for key in keys:
if key in d[url]:
self.session.headers.update({key: d[url][key]})
else:
self.session.headers.update({key: None})
def get(self, url):
self.updateHeaders(url)
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))
continue
except requests.exceptions.Timeout as e:
print('Timeout(%s): e=%s' % (url, e))
continue
except requests.exceptions.TooManyRedirects as e:
print('TooManyRedirects(%s): e=%s' % (url, e))
continue
except requests.exceptions.HTTPError as e:
print('HTTPError(%s): e=%s' % (url, e))
continue
except requests.exceptions.RequestException as e:
print('RequestException(%s): e=%s' % (url, e))
continue
except:
print('Unknown exception(%s)' % (url))
continue
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.updateHeaders(url)
if url == 'https://kyfw.12306.cn/otn/passcodeNew/checkRandCodeAnsyn':
if payload.find('REPEAT_SUBMIT_TOKEN') != -1:
self.session.headers.update({'Referer': 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'})
else:
self.session.headers.update({'Referer': 'https://kyfw.12306.cn/otn/login/init'})
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))
continue
except requests.exceptions.Timeout as e:
print('Timeout(%s): e=%s' % (url, e))
continue
except requests.exceptions.TooManyRedirects as e:
print('TooManyRedirects(%s): e=%s' % (url, e))
continue
except requests.exceptions.HTTPError as e:
print('HTTPError(%s): e=%s' % (url, e))
continue
except requests.exceptions.RequestException as e:
print('RequestException(%s): e=%s' % (url, e))
continue
except:
print('Unknown exception(%s)' % (url))
continue
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 transposition(self, posList):
posDict = {
"1" : "65,65,",
"2" : "130,65,",
"3" : "195,65,",
"4" : "260,65,",
"5" : "65,130,",
"6" : "130,130,",
"7" : "195,130,",
"8" : "260,130,",
}
randstr = ""
for p in posList:
randstr += posDict[p]
return randstr[0:-1]
def getCaptcha(self, url):
self.updateHeaders(url)
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位图片验证码(回车刷新验证码):')
captcha = raw_input()
if not len(captcha) >= 1:
return RET_ERR
else:
captcha = str(captcha)
posList = captcha.split(",")
for p in posList:
if int(p) > 8:
print(u'验证码不合规,应该小于等于8!')
return RET_ERR
return self.transposition(posList)
def initStation(self):
url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js'
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('|') # bji|北京|BJP|beijing|bj|2
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))
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:
print(u'出发站错误, 请重新输入')
station = inputStation()
self.from_city_name = station['name']
self.from_station_telecode = station['telecode']
# 检查目的站
station = getStationByName(self.to_city_name)
if not station:
print(u'目的站错误,请重新输入')
station = inputStation()
self.to_city_name = station['name']
self.to_station_telecode = station['telecode']
# 检查乘车日期
if not checkDate(self.train_date):
print(u'乘车日期无效, 请重新选择')
self.train_date = selectDate()
# 分析乘客信息
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 checkRandCodeAnsyn(self, module):
d = {
'login': { # 登陆验证码
'rand': 'sjrand',
'referer': 'https://kyfw.12306.cn/otn/login/init'
},
'passenger': { # 订单验证码
'rand': 'randp',
'referer': 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'
}
}
if not module in d:
print(u'无效的 module: %s' % (module))
return RET_ERR
tries = 0
while tries < MAX_TRIES:
tries += 1
url = 'https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=%s&rand=%s&' % (module, d[module]['rand'])
if tries > 1:
url = '%s%1.16f' % (url, random.random())
print(u'正在等待验证码...')
self.captcha = self.getCaptcha(url)
if not self.captcha:
continue
if self.captcha == 1: # 刷新不计数
tries -= 1
continue
url = 'https://kyfw.12306.cn/otn/passcodeNew/checkRandCodeAnsyn'
parameters = [
('randCode', self.captcha),
('rand', d[module]['rand'])
]
if module == 'login':
parameters.append(('randCode_validate', ''))
else:
parameters.append(('_json_att', ''))
parameters.append(('REPEAT_SUBMIT_TOKEN', self.repeatSubmitToken))
payload = urllib.urlencode(parameters)
print(u'正在校验验证码...')
r = self.post(url, payload)
if not r:
print(u'校验验证码异常')
continue
# {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"result":"1","msg":"randCodeRight"},"messages":[],"validateMessages":{}}
obj = r.json()
if (
hasKeys(obj, ['status', 'httpstatus', 'data'])
and hasKeys(obj['data'], ['result', 'msg'])
and (obj['data']['result'] == '1')):
print(u'校验验证码成功')
return RET_OK
else:
print(u'校验验证码失败')
dumpObj(obj)
continue
else:
return RET_ERR
def login(self):
url = 'https://kyfw.12306.cn/otn/login/init'
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']
if self.checkRandCodeAnsyn('login') == RET_ERR:
return RET_ERR
print(u'正在登录...')
url = 'https://kyfw.12306.cn/otn/login/loginAysnSuggest'
parameters = [
('loginUserDTO.user_name', self.username),
('userDTO.password', self.password),
('randCode', self.captcha),
('randCode_validate', ''),
#('ODg3NzQ0', 'OTIyNmFhNmQwNmI5ZmQ2OA%3D%3D'),
('myversion', 'undefined')
]
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'登陆成功^_^')
url = 'https://kyfw.12306.cn/otn/login/userLogin'
parameters = [
('_json_att', ''),
]
payload = urllib.urlencode(parameters)
r = self.post(url, payload)
return RET_OK
else:
print(u'登陆失败啦!重新登陆...')
dumpObj(obj)
return RET_ERR
def getPassengerDTOs(self):
url = 'https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs'
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 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':
self.printConfig()
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):
self.canWebBuy = False
url = 'https://kyfw.12306.cn/otn/leftTicket/init'
parameters = [
('_json_att', ''),
('leftTicketDTO.from_station_name', self.from_city_name),
('leftTicketDTO.to_station_name', self.to_city_name),
('leftTicketDTO.from_station', self.from_station_telecode),
('leftTicketDTO.to_station', self.to_station_telecode),
('leftTicketDTO.train_date', self.train_date),
('back_train_date', self.back_train_date),
('purpose_codes', self.purpose_code),
('pre_step_flag', 'index')
]
payload = urllib.urlencode(parameters)
r = self.post(url, payload)
if not r:
print(u'查询车票异常')
url = 'https://kyfw.12306.cn/otn/leftTicket/log?'
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'查询车票异常')
url = 'https://kyfw.12306.cn/otn/leftTicket/query?'
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'])
# Add the From: To: and Subject: headers at the start!
msg = {}
msg['Subject'] = u'余票信息'
msg['From'] = me
msg['From'] = self.notify['mail_username']
msg['To'] = ';'.join(self.notify['mail_to'])
msg['content'] = self.notify['mail_content']
mcontent = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
% (msg['From'], msg['To'], msg['Subject']))
mcontent += msg['content']
print mcontent
try:
server = smtplib.SMTP_SSL(host='smtp.qq.com', port=465)
# server = smtplib.SMTP_SSL()
# server.set_debuglevel(1) # 开启调试,会打印调试信息
# server.connect(self.notify['mail_server'],465)
# print self.notify['mail_password']
# print self.notify['mail_username']
server.login(
self.notify['mail_username'],
self.notify['mail_password'])
server.sendmail(me, self.notify['mail_to'], mcontent)
server.quit()
print(u'发送邮件提醒成功')
return True
except Exception as e:
print(u'发送邮件提醒失败, %s' % str(e))
return False
def parseTrains(self):
'''
一 二 商 特 软 硬 座 无
-4 -5 -3 X -12 -7 -6 -7
'''
if not self.trains.has_key('map'): return RET_ERR
if self.trains.has_key('map'):mapDict = self.trains['map']
if self.trains.has_key('result'):data = self.trains['result']
retlist = []
retdict = {}
self.trainsinfo = []
for train in data:
for s in mapDict.keys():
if s in train: train = train.replace(s,mapDict[s])
train = train.split("|")
retdict['trainNo'] = train[3]
retdict['secretStr'] = train[0]
retdict['leftTicket'] = train[12]
retdict['train_location'] = train[15]
retdict['startS'] = train[4]
retdict['desS'] = train[7]
retdict['start_time'] = train[8]
retdict['des_time'] = train[9]
retdict['lishi'] = train[10]
retdict['traindate'] = train[13]
retdict['canWebBuy'] = train[11]
retdict['zy'] = train[-4] if len(train[-4]) > 0 else "--"
retdict['ze'] = train[-5] if len(train[-5]) > 0 else "--"
retdict['swz'] = train[-3] if len(train[-3]) > 0 else "--"
retdict['rw'] = train[-12] if len(train[-12]) > 0 else "--"
retdict['yw'] = train[-7] if len(train[-7]) > 0 else "--"
retdict['yz'] = train[-6] if len(train[-6]) > 0 else "--"
retdict['wz'] = "--"
self.trainsinfo.append(retdict)
retdict = {}
retlist = []
return RET_OK
def printTrains(self):
seatTypeCode = {
'swz': '商务座',
'tz': '特等座',
'zy': '一等座',
'ze': '二等座',
'gr': '高级软卧',
'rw': '软卧',
'yw': '硬卧',
'rz': '软座',
'yz': '硬座',
'wz': '无座',
'qt': '其它',
}
printDelimiter()
if self.parseTrains() == RET_ERR: return RET_ERR