-
Notifications
You must be signed in to change notification settings - Fork 107
/
Copy pathnew.py
1224 lines (1142 loc) · 45.9 KB
/
new.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/python
# -*- coding: utf-8 -*-
import argparse
import cookielib
import urllib
import urllib2
import json
import time
import sys
import re
import ConfigParser
import codecs
import random
#import logging
import smtplib
from email.mime.text import MIMEText
from StringIO import StringIO
from PIL import Image
# Global variables
stations = []
RET_OK = 0
RET_ERR = -1
# Set default encoding to utf-8
reload(sys)
sys.setdefaultencoding('utf-8')
#------------------------------------------------------------------------------
# 分隔线
def printDelimiter():
print '-'*100
#------------------------------------------------------------------------------
# 火车站点数据库初始化
# 全部站点, 数据来自: https://kyfw.12306.cn/otn/resources/js/framework/station_name.js
# 每个站的格式如下:
# @bji|北京|BJP|beijing|bj|2 ---> @拼音缩写三位|站点名称|编码|拼音|拼音缩写|序号
def stationInit():
url = "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js"
referer = "https://kyfw.12306.cn/otn/"
resp = sendGetRequest(url, referer)
try:
data = resp.read().decode("utf-8","ignore")
if data.find("'@") != -1:
station_names = data[data.find("'@"):]
else:
print(u"读取站点信息失败")
return {}
except:
print(u"读取站点信息异常")
sys.exit()
station_list = station_names.split('@')
station_list = station_list[1:] # The first one is empty, skip it
for station in station_list:
items = station.split('|') # bjb|北京北|VAP|beijingbei|bjb|0
stations.append({'abbr':items[0], 'name':items[1], 'telecode':items[2], 'pinyin':items[4]})
return stations
#------------------------------------------------------------------------------
# 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:
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') # time.struct_time(tm_year=2014, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=1, tm_isdst=-1)
asc = time.asctime(t) # 'Wed Jan 01 00:00:00 2014'
return (asc[0:-4] + 'UTC+0800 ' + asc[-4:]) # 'Wed Jan 01 00:00:00 UTC+0800 2014'
#------------------------------------------------------------------------------
# 证件类型
def getCardType(cardtype):
d = {
'1':u"二代身份证",
'2':u"一代身份证",
'C':u"港澳通行证",
'G':u"台湾通行证",
'B':u"护照"
}
if d.has_key(cardtype):
return d[cardtype]
else:
return u"未知证件类型"
#------------------------------------------------------------------------------
# 席别:
def getSeatType(seattype):
d = {
'1':u"硬座",#硬座/无座
'3':u"硬卧",
'4':u"软卧",
'7':u"一等软座",
'8':u"二等软座",
'9':u"商务座",
'M':u"一等座",
'O':u"二等座",
'P':u"特等座"
}
if d.has_key(seattype):
return d[seattype]
else:
return u"未知席别"
#------------------------------------------------------------------------------
# 票种类型
def getTicketType(tickettype):
d = {
'1':u"成人票",
'2':u"儿童票",
'3':u"学生票",
'4':u"残军票"
}
if d.has_key(tickettype):
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:
return 1
else:
return 0
#------------------------------------------------------------------------------
# Input date
def inputDate(prompt=u"请输入乘车日期:"):
train_date = ''
while 1:
print(prompt)
train_date = raw_input('')
if checkDate(train_date):
break
else:
print u"格式错误,请重新输入有效的乘车日期,如2014-02-01:"
return train_date
#------------------------------------------------------------------------------
# Input station
def inputStation(prompt=''):
station = None
print prompt,
print u'(支持中文,拼音和拼音缩写,如:北京,beijing,bj)'
while 1:
name = raw_input().decode("gb2312","ignore")
station = getStationByName(name)
if station:
return station
else:
print u"站点错误,没有站点'%s',请重新输入:"%(name)
#------------------------------------------------------------------------------
# Send post request
def sendPostRequest(url, data, referer='https://kyfw.12306.cn/otn/index/init'):
post_timeout = 300
req = urllib2.Request(url, data)
req.add_header('Content-Type', "application/x-www-form-urlencoded")
req.add_header('Referer', referer)
resp = None
tries = 0
max_tries = 3
while tries < max_tries:
tries += 1
try:
resp = urllib2.urlopen(req, timeout=post_timeout*tries)
except urllib2.HTTPError,e:
print("Post %d times %s exception HTTPError code:"%(tries, url), e.code)
except urllib2.URLError,e:
print("Post %d times %s exception URLError reason:"%(tries, url), e.reason)
except:
print("Post %d times %s exception other"%(tries, url))
if resp:
break
return resp
#------------------------------------------------------------------------------
# Send get request
def sendGetRequest(url,referer='https://kyfw.12306.cn/otn/index/init'):
get_timeout = 150
req = urllib2.Request(url)
req.add_header('Referer', referer)
resp = None
tries = 0
max_tries = 3
while tries < max_tries:
tries += 1
try:
resp = urllib2.urlopen(req,timeout=get_timeout*tries)
except urllib2.HTTPError,e:
print("Get %d times %s exception HTTPError code:"%(tries, url), e.code)
except urllib2.URLError,e:
print("Get %d times %s exception URLError reason:"%(tries, url), e.reason)
except:
print("Get %d times %s exception other"%(tries, url))
if resp:
break
return resp
#------------------------------------------------------------------------------
# 保存验证码图片到本地, 再手动输入
def getCaptcha(url, module, rand):
randUrl = 'https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew.do?module=%s&rand=%s'%(module, rand);
captcha = ''
while 1:
im = Image.open(StringIO(urllib2.urlopen(url).read()))
im.save("captcha.gif")
print u"请输入4位图片验证码(直接回车刷新):"
url = "%s&%1.16f"%(randUrl, random.random())
captcha = raw_input("")
if len(captcha) == 4:
return captcha
#------------------------------------------------------------------------------
# Convert json string to dict object
def data2Json(data, keys):
if not data:
return {}
try:
obj = json.loads(data);
except:
print(u'data2Json() exception')
return {}
if not (obj and set(keys).issubset(obj)):
print(u'data2Json() failed')
return {}
#print json.dumps(obj, indent=2)
return obj
#------------------------------------------------------------------------------
# Select train
def selectTrain(trains):
trains_num = len(trains)
index = 0
while 1: # 必须选择有效的车次
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 = [] # 乘客列表
self.trains = [] # 列车列表, 查询余票后自动更新
self.current_train_index = 0 # 当前选中的列车索引序号
self.captcha = '' # 图片验证码
self.orderId = '' # 订单流水号
self.notify = {
'mail_enable':0,
'mail_username':'',
'mail_password':'',
'mail_server':'',
'mail_to':[],
'trains':[],
'xb':[],
'focus':{}
}
def readConfig(self,config_file='config.ini'):
# 从配置文件读取订票信息
cp = ConfigParser.ConfigParser()
try:
cp.readfp(codecs.open(config_file, 'r','utf-8-sig'))
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['trains'] = cp.get("notify","trains").split(',')
self.notify['xb'] = cp.get("notify","xb").split(',')
'''
focus = {
'K9062':['yw', 'yz'],
'K9060':['yw', 'yz'],
}
'''
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"订票信息:"
print u"%s\t%s\t%s--->%s"%(self.username,self.train_date,self.from_city_name,self.to_city_name)
printDelimiter()
print u"序号 姓名\t证件类型\t证件号码\t\t席别\t票种\t"
for p in self.passengers:
print u"%d %s\t%s\t%s\t%s\t%s"%(p['index'],p['name'].decode("utf-8","ignore"),getCardType(p['cardtype']),p['id'],getSeatType(p['seattype']),getTicketType(p['tickettype']))
def initCookieJar(self):
self.cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
opener.addheaders = [
('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'),
]
urllib2.install_opener(opener)
def login(self):
url = "https://kyfw.12306.cn/otn/login/init"
referer = "https://kyfw.12306.cn/otn/"
resp = sendGetRequest(url, referer)
tries = 0
while tries < 3:
tries += 1
print(u"接收登录验证码...")
url = 'https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=login&rand=sjrand'
if self.cj._cookies['kyfw.12306.cn']['/otn']['JSESSIONID'].value:
url = 'https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew;jsessionid=%s?module=login&rand=sjrand'%(self.cj._cookies['kyfw.12306.cn']['/otn']['JSESSIONID'].value)
self.captcha = getCaptcha(url, 'login', 'sjrand')
print(u"正在校验登录验证码...")
url = 'https://kyfw.12306.cn/otn/passcodeNew/checkRandCodeAnsyn'
referer = 'https://kyfw.12306.cn/otn/login/init'
parameters = [
('randCode', self.captcha),
('rand', "sjrand"),
]
postData = urllib.urlencode(parameters)
resp = sendPostRequest(url, postData, referer)
try:
data = resp.read()
except:
print(u"校验登录验证码异常")
continue
# {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":"Y","messages":[],"validateMessages":{}}
# {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":"N","messages":[],"validateMessages":{}}
obj = data2Json(data, ('status', 'httpstatus', 'data'))
if not (obj and obj['status'] and (obj['data'] == 'Y')):
print(u"校验登录验证码失败")
if obj.has_key('messages') and obj['messages']: # 打印错误信息
print json.dumps(obj['messages'], ensure_ascii=False, indent=2)
continue
else:
print(u"校验登录验证码成功")
break
else:
print(u'尝试次数太多,自动退出程序以防账号被冻结')
sys.exit()
print(u"正在登录...")
url = "https://kyfw.12306.cn/otn/login/loginAysnSuggest"
referer = "https://kyfw.12306.cn/otn/login/init"
parameters = [
('loginUserDTO.user_name', self.username),
('userDTO.password', self.password),
('randCode', self.captcha),
]
postData = urllib.urlencode(parameters)
resp = sendPostRequest(url, postData, referer)
try:
data = resp.read()
except:
print(u"登录异常")
return RET_ERR
# {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{},"messages":["密码输入错误,您还有3次机会!"],"validateMessages":{}}
# {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"loginCheck":"Y"},"messages":[],"validateMessages":{}}
obj = data2Json(data, ('status', 'httpstatus', 'data'))
if not (obj and obj['data'].has_key('loginCheck') and (obj['data']['loginCheck'] == 'Y')):
print(u"登陆失败啦!重新登陆...")
if obj.has_key('messages') and obj['messages']: # 打印错误信息
print json.dumps(obj['messages'], ensure_ascii=False, indent=2)
return RET_ERR
# 可以省略的步骤
'''
url = "https://kyfw.12306.cn/otn/login/userLogin"
referer = "https://kyfw.12306.cn/otn/login/init"
parameters = [
('_json_att', ""),
]
postData = urllib.urlencode(parameters)
resp = sendPostRequest(url, postData, referer)
'''
print(u"登陆成功^_^")
return RET_OK
def loginProc(self):
tries = 0
while tries < 3:
tries += 1
printDelimiter()
if self.login() == RET_OK:
break
else:
print u"失败次数太多,自动退出程序"
sys.exit()
def queryTickets(self):
# 可以省略的步骤
'''
url = 'https://kyfw.12306.cn/otn/index/init'
referer = 'https://kyfw.12306.cn/otn/login/init'
resp = sendGetRequest(url, referer)
'''
# 可以省略的步骤
'''
url = "https://kyfw.12306.cn/otn/leftTicket/init"
referer = "https://kyfw.12306.cn/otn/index/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),
('flag', self.tour_flag),
('purpose_code', self.purpose_code),
('pre_step_flag', 'index'),
]
postData = urllib.urlencode(parameters)
resp = sendPostRequest(url, postData, referer)
try:
data = resp.read()
except:
print(u"查询车票初始化异常")
return RET_ERR
'''
# 可以省略的步骤
#self.captcha = getCaptcha('https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=login&rand=sjrand', 'login', 'sjrand')
url = 'https://kyfw.12306.cn/otn/leftTicket/query?'
referer = 'https://kyfw.12306.cn/otn/leftTicket/init'
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)
resp = sendGetRequest(url, referer)
try:
data = resp.read()
except:
print(u"查询车票异常")
return RET_ERR
obj = data2Json(data, ('status', 'httpstatus', 'data'))
if not (obj and len(obj['data'])):
print(u'查询车票失败')
return RET_ERR
else:
self.trains = obj['data']
return RET_OK
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, e:
print(u'发送邮件提醒失败')
print 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目的站\tstart\tarrive\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\t%s\t%s%s"%(index,
t['station_train_code'],
t['from_station_name'],
t['to_station_name'],
t['start_time'],
t['arrive_time'],
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 = ''
if self.notify['focus'].has_key('all'): # 任意车次
if self.notify['focus']['all'][0] == 'all': # 任意席位
msg = u'车次:%s已经有票啦\n'%(t['station_train_code'])
else: # 指定席位
for seat in self.notify['focus']['all']:
if ypInfo.has_key(seat) and ypInfo[seat]['left']:
msg += u'座位类型:%s, 剩余车票数量:%s, 票价:%s \n'%(seat if not seatTypeCode.has_key(seat) else seatTypeCode[seat], ypInfo[seat]['left'], ypInfo[seat]['price'])
if msg:
msg = u'车次:%s现在有票啦\n'%(t['station_train_code']) + msg + u'\n'
elif self.notify['focus'].has_key(t['station_train_code']): # 指定车次
if self.notify['focus'][t['station_train_code']][0] == 'all': # 任意席位
msg = u'车次:%s已经有票啦\n'%(t['station_train_code'])
else: # 指定席位
for seat in self.notify['focus'][t['station_train_code']]:
if ypInfo.has_key(seat) and ypInfo[seat]['left']:
msg += u'座位类型:%s, 剩余车票数量:%s, 票价:%s \n'%(seat if not seatTypeCode.has_key(seat) else seatTypeCode[seat], ypInfo[seat]['left'], ypInfo[seat]['price'])
if msg:
msg = u'车次:%s现在有票啦\n'%(t['station_train_code']) + 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:
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"您可以选择:\n1~%d.选择车次开始订票\nd.更改乘车日期\nf.更改出发站\nt.更改目的站\ns.同时更改出发站和目的站\na.同时更改乘车日期,出发站和目的站\nu.查询未完成订单\nq.退出\n刷新车票请直接回车"%(trains_num)
printDelimiter()
select = raw_input("")
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 == "d" or select == "D":
self.train_date = inputDate()
elif select == "f" or select == "F":
station = inputStation(u"请输入出发站:")
self.from_city_name = station['name']
self.from_station_telecode = station['telecode']
elif select == "t" or select == "T":
station = inputStation(u"请输入目的站:")
self.to_city_name = station['name']
self.to_station_telecode = station['telecode']
elif select == "s" or select == "S":
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 == "a" or 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" or select == "U":
ret = self.queryMyOrderNotComplete()
ret = self.selectAction()
elif select == "q" or select == "Q":
ret = 0
return ret
def initOrder(self):
# 可以省略的步骤
# 检查登录
'''
url = 'https://kyfw.12306.cn/otn/login/checkUser'
referer = 'https://kyfw.12306.cn/otn/leftTicket/init'
parameters = [
('_json_att', ''),
]
postData = urllib.urlencode(parameters)
resp = sendPostRequest(url, postData, referer)
try:
data = resp.read()
except:
print(u"检查登录异常")
return RET_ERR
# {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"flag":true},"messages":[],"validateMessages":{}}
obj = data2Json(data, ('status', 'httpstatus', 'data'))
if not (obj and obj['data'].has_key('flag') and obj['data']['flag']):
print(u"你好像还没有登录哦")
if obj.has_key('messages') and obj['messages']: # 打印错误信息
print json.dumps(obj['messages'], ensure_ascii=False, indent=2)
return RET_ERR
'''
print(u"准备下单喽")
url = 'https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest'
referer = 'https://kyfw.12306.cn/otn/leftTicket/init'
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)
postData = ''
length = len(parameters);
for i in range(0, length):
postData += parameters[i][0] + '=' + parameters[i][1]
if i < (length - 1):
postData += '&'
resp = sendPostRequest(url, postData, referer)
try:
data = resp.read()
except:
print(u"下单异常")
return RET_ERR
# {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"messages":[],"validateMessages":{}}
obj = data2Json(data, ('status', 'httpstatus'))
if not (obj and obj['status']):
print(u"下单失败啦")
if obj.has_key('messages') and obj['messages']: # 打印错误信息
print json.dumps(obj['messages'], ensure_ascii=False, indent=2)
#print ','.join(obj['messages'])
return RET_ERR
print(u"订单初始化...")
url = 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'
referer = 'https://kyfw.12306.cn/otn/leftTicket/init'
parameters = [
('_json_att', ''),
]
postData = urllib.urlencode(parameters)
resp = sendPostRequest(url, postData, referer)
try:
data = resp.read()
except:
print(u"订单初始化异常")
return RET_ERR
s = data.find('globalRepeatSubmitToken') # TODO
e = data.find('global_lang')
if s == -1 or e == -1:
print(u'找不到 globalRepeatSubmitToken')
return RET_ERR
buf = data[s:e]
s = buf.find("'")
e = buf.find("';")
if s == -1 or e == -1:
print(u'很遗憾, 找不到 globalRepeatSubmitToken')
return RET_ERR
self.repeatSubmitToken = buf[s+1:e]
s = data.find('key_check_isChange')
e = data.find('leftDetails')
if s == -1 or e == -1:
print(u'找不到 key_check_isChange')
return RET_ERR
self.keyCheckIsChange = data[s+len('key_check_isChange')+3:e-3]
return RET_OK
def checkOrderInfo(self):
# 可以省略的步骤
'''
url = 'https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs'
referer = 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'
parameters = [
('_json_att', ''),
('REPEAT_SUBMIT_TOKEN', self.repeatSubmitToken),
]
postData = urllib.urlencode(parameters)
resp = sendPostRequest(url, postData, referer)
'''
tries = 0
while tries < 3:
tries += 1
print(u"接收订单验证码...")
self.captcha = getCaptcha("https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=passenger&rand=randp", 'passenger', 'randp')
print(u"正在校验订单验证码...")
url = 'https://kyfw.12306.cn/otn/passcodeNew/checkRandCodeAnsyn'
referer = 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'
parameters = [
('randCode', self.captcha),
('rand', 'randp'),
('_json_att', ''),
('REPEAT_SUBMIT_TOKEN', self.repeatSubmitToken),
]
postData = urllib.urlencode(parameters)
resp = sendPostRequest(url, postData, referer)
try:
data = resp.read()
except:
print(u"校验订单验证码异常")
continue
# {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":"Y","messages":[],"validateMessages":{}}
obj = data2Json(data, ('status', 'httpstatus', 'data'))
if not (obj and obj['status'] and (obj['data'] == 'Y')):
print(u"校验订单验证码失败")
if obj.has_key('messages') and obj['messages']: # 打印错误信息
print json.dumps(obj['messages'], ensure_ascii=False, indent=2)
continue
else:
print(u"校验订单验证码成功")
break
else:
print(u'尝试次数太多,请重试')
return RET_ERR
passengerTicketStr = ''
oldPassengerStr = ''
passenger_seat_detail = "0" # [0->随机][1->下铺][2->中铺][3->上铺]
for p in self.passengers:
if p['index'] != 1:
passengerTicketStr += 'N_'
oldPassengerStr += '1_'
passengerTicketStr += '%s,%s,%s,%s,%s,%s,%s,'%(p['seattype'],passenger_seat_detail,p['tickettype'],p['name'],p['cardtype'],p['id'],p['phone'])
oldPassengerStr += '%s,%s,%s,'%(p['name'],p['cardtype'],p['id'])
passengerTicketStr += 'N'
oldPassengerStr += '1_'
self.passengerTicketStr = passengerTicketStr
self.oldPassengerStr = oldPassengerStr
print(u"检查订单...")
url = 'https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo'
referer = 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'
parameters = [
('cancel_flag', '2'), # TODO
('bed_level_order_num', '000000000000000000000000000000'), # TODO
('passengerTicketStr', self.passengerTicketStr),
('oldPassengerStr', self.oldPassengerStr),
('tour_flag', self.tour_flag),
('randCode', self.captcha),
('_json_att', ''),
('REPEAT_SUBMIT_TOKEN', self.repeatSubmitToken),
]
postData = urllib.urlencode(parameters)
resp = sendPostRequest(url, postData, referer)
try:
data = resp.read()
except:
print(u"检查订单异常")
return RET_ERR
# {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"submitStatus":true},"messages":[],"validateMessages":{}}
# {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"errMsg":"非法的席别,请重新选择!","submitStatus":false},"messages":[],"validateMessages":{}}
obj = data2Json(data, ('status', 'httpstatus', 'data'))
if not (obj and obj['status'] and obj['data'].has_key('submitStatus') and obj['data']['submitStatus']):
print(u"检查订单失败")
if obj.has_key('messages') and obj['messages']: # 打印错误信息
print json.dumps(obj['messages'], ensure_ascii=False, indent=2)
if obj['data'].has_key('errMsg') and obj['data']['errMsg']: # 打印错误信息
print json.dumps(obj['data']['errMsg'], ensure_ascii=False, indent=2)
return RET_ERR
return RET_OK
def getQueueCount(self):
print(u"查询排队情况...")
url = 'https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount'
referer = 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'
t = self.trains[self.current_train_index]['queryLeftNewDTO']
parameters = [
('train_date', trainDate(self.train_date)),
('train_no', t['train_no']),
('stationTrainCode', t['station_train_code']),
('seatType', '1'), # TODO
('fromStationTelecode', t['from_station_telecode']),
('toStationTelecode', t['to_station_telecode']),
('leftTicket', t['yp_info']),
('purpose_codes', '00'), # TODO
('_json_att', ''),
('REPEAT_SUBMIT_TOKEN', self.repeatSubmitToken)
]
postData = urllib.urlencode(parameters)
resp = sendPostRequest(url, postData, referer)
try:
data = resp.read()
except:
print(u"查询排队情况异常")
return RET_ERR
# {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"count":"0","ticket":"1007803168402230000010078003803014400024","op_2":"false","countT":"0","op_1":"false"},"messages":[],"validateMessages":{}}
obj = data2Json(data, ('status', 'httpstatus', 'data'))
if not (obj and obj['status'] and obj['data'].has_key('op_1') and obj['data'].has_key('op_2')):
print(u"查询排队情况失败")
if obj.has_key('messages') and obj['messages']: # 打印错误信息
print json.dumps(obj['messages'], ensure_ascii=False, indent=2)
return RET_ERR
if obj['data']['op_1'] != "false":
print(u'目前排队人数已经超过余票张数,特此提醒。今日已有人先于您提交相同的购票需求,到处理您的需求时可能已无票,建议你们根据当前余票确定是否排队。')
if obj['data']['op_2'] != "false":
print(u'目前排队人数已经超过余票张数,请您选择其他席别或车次,特此提醒。')
if obj['data'].has_key('ticket'):
print(u'排队详情:%s'%(obj['data']['ticket'])) # TODO
return RET_OK
def confirmSingleForQueue(self):
print(u"提交订单排队...")
url = 'https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue'
referer = 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'
t = self.trains[self.current_train_index]['queryLeftNewDTO']
parameters = [
('passengerTicketStr', self.passengerTicketStr),
('oldPassengerStr', self.oldPassengerStr),
('randCode', self.captcha),
('purpose_codes', '00'), # TODO
('key_check_isChange', self.keyCheckIsChange),
('leftTicketStr', t['yp_info']),
('train_location', t['location_code']),
('_json_att', ''),
('REPEAT_SUBMIT_TOKEN', self.repeatSubmitToken),
]
postData = urllib.urlencode(parameters)