优化查询速度

remotes/test12306/master
wenxianping 2018-01-09 15:05:56 +08:00
parent 3c9bf71b0f
commit 34dbcdb97a
1 changed files with 88 additions and 76 deletions

View File

@ -171,6 +171,24 @@ class select:
print("未查找到常用联系人") print("未查找到常用联系人")
raise PassengerUserException("未查找到常用联系人,请先添加联系人在试试") raise PassengerUserException("未查找到常用联系人,请先添加联系人在试试")
def leftTicketLog(self, from_station, to_station):
"""
模拟进入车次列表页
:param from_station:
:param to_station:
:return:
"""
leftTicketLogUrl = 'https://kyfw.12306.cn/otn/leftTicket/log?leftTicketDTO.train_date={0}&leftTicketDTO.from_station={1}&leftTicketDTO.to_station={2}&purpose_codes=ADULT'.format(
self.station_date, from_station, to_station)
leftTicketLog = json.loads(myurllib2.get(leftTicketLogUrl), encoding='utf-8')
if "status" in leftTicketLog and leftTicketLog["status"] is True:
return True
else:
if "message" in leftTicketLog and leftTicketLog["message"]:
print leftTicketLog["message"]
elif "validateMessages" in leftTicketLog and leftTicketLog["validateMessages"]:
print leftTicketLog["validateMessages"]
def submitOrderRequest(self, from_station, to_station): def submitOrderRequest(self, from_station, to_station):
""" """
提交车次信息 提交车次信息
@ -187,54 +205,47 @@ class select:
:return: :return:
""" """
select_url = 'https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date={0}&leftTicketDTO.from_station={1}&leftTicketDTO.to_station={2}&purpose_codes=ADULT'.format(self.station_date, from_station, to_station) select_url = 'https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date={0}&leftTicketDTO.from_station={1}&leftTicketDTO.to_station={2}&purpose_codes=ADULT'.format(self.station_date, from_station, to_station)
leftTicketLogUrl = 'https://kyfw.12306.cn/otn/leftTicket/log?leftTicketDTO.train_date={0}&leftTicketDTO.from_station={1}&leftTicketDTO.to_station={2}&purpose_codes=ADULT'.format(self.station_date, from_station, to_station) station_ticket = json.loads(myurllib2.get(select_url), encoding='utf-8')
leftTicketLog = json.loads(myurllib2.get(leftTicketLogUrl), encoding='utf-8') value = station_ticket['data']
if "status" in leftTicketLog and leftTicketLog["status"] is True: if not value:
station_ticket = json.loads(myurllib2.get(select_url), encoding='utf-8') print ('{0}-{1} 车次坐席查询为空...'.format(self.from_station, self.to_station))
value = station_ticket['data']
if not value:
print ('{0}-{1} 车次坐席查询为空...'.format(self.from_station, self.to_station))
else:
if value['result']:
for i in value['result']:
ticket_info = i.split('|')
if ticket_info[11] == "Y" and ticket_info[1] == "预订": # 筛选未在开始时间内的车次
for j in range(len(self._station_seat)):
is_ticket_pass = ticket_info[self.station_seat(self._station_seat[j].encode("utf8"))]
# print self._station_seat[j]
if is_ticket_pass != '' and is_ticket_pass != '' and ticket_info[3] in self.station_trains and is_ticket_pass != '*': # 过滤有效目标车次
# tiket_values = [k for k in value['map'].values()]
self.secretStr = ticket_info[0]
train_no = ticket_info[3]
print ('车次: ' + train_no + ' 始发车站: ' + self.to_station + ' 终点站: ' +
self.to_station + ' ' + self._station_seat[j].encode("utf8") + ':' + ticket_info[self.station_seat(self._station_seat[j].encode("utf8"))])
if self.ticket_black_list.has_key(train_no) and (self.ticket_black_list["train_no"] - datetime.datetime.now()).seconds/60 < self.ticket_black_list_time:
print("该车次{} 正在被关小黑屋,跳过此车次".format(train_no))
else:
print ('正在尝试提交订票...')
if self.check_user():
self.submit_station()
self.getPassengerTicketStr(self._station_seat[j].encode("utf8"))
self.getRepeatSubmitToken()
self.user_info = self.getPassengerDTOs()
if self.checkOrderInfo():
if self.getQueueCount(train_no, self._station_seat[j].encode("utf8")):
break
else:
pass
print "当前车次{0} 查询无符合条件坐席,正在重新查询".format(ticket_info[3])
elif ticket_info[11] == "N":
print("当前车次{0} 无票".format(ticket_info[3]))
else:
print("当前这次还处于待售状态,请耐心等待")
time.sleep(self.expect_refresh_interval)
else:
raise ticketConfigException("车次配置信息有误,请检查")
else: else:
if "message" in leftTicketLog and leftTicketLog["message"]: if value['result']:
print leftTicketLog["message"] for i in value['result']:
elif "validateMessages" in leftTicketLog and leftTicketLog["validateMessages"]: ticket_info = i.split('|')
print leftTicketLog["validateMessages"] if ticket_info[11] == "Y" and ticket_info[1] == "预订": # 筛选未在开始时间内的车次
for j in range(len(self._station_seat)):
is_ticket_pass = ticket_info[self.station_seat(self._station_seat[j].encode("utf8"))]
# print self._station_seat[j]
if is_ticket_pass != '' and is_ticket_pass != '' and ticket_info[3] in self.station_trains and is_ticket_pass != '*': # 过滤有效目标车次
# tiket_values = [k for k in value['map'].values()]
self.secretStr = ticket_info[0]
train_no = ticket_info[3]
print ('车次: ' + train_no + ' 始发车站: ' + self.from_station + ' 终点站: ' +
self.to_station + ' ' + self._station_seat[j].encode("utf8") + ':' + ticket_info[self.station_seat(self._station_seat[j].encode("utf8"))])
if self.ticket_black_list.has_key(train_no) and (self.ticket_black_list["train_no"] - datetime.datetime.now()).seconds/60 < self.ticket_black_list_time:
print("该车次{} 正在被关小黑屋,跳过此车次".format(train_no))
else:
print ('正在尝试提交订票...')
if self.check_user():
self.submit_station()
self.getPassengerTicketStr(self._station_seat[j].encode("utf8"))
self.getRepeatSubmitToken()
self.user_info = self.getPassengerDTOs()
if self.checkOrderInfo():
if self.getQueueCount(train_no, self._station_seat[j].encode("utf8")):
break
else:
pass
print "当前车次{0} 查询无符合条件坐席,正在重新查询".format(ticket_info[3])
elif ticket_info[11] == "N":
print("当前车次{0} 无票".format(ticket_info[3]))
else:
print("当前这次还处于待售状态,请耐心等待")
time.sleep(self.expect_refresh_interval)
else:
raise ticketConfigException("车次配置信息有误,请检查")
def check_user(self): def check_user(self):
""" """
@ -548,36 +559,37 @@ class select:
def main(self): def main(self):
from_station, to_station = self.station_table(self.from_station, self.to_station) from_station, to_station = self.station_table(self.from_station, self.to_station)
num = 1 if self.leftTicketLog(from_station, to_station):
while 1: num = 1
try: while 1:
num += 1 try:
time.sleep(self.select_refresh_interval) num += 1
if time.strftime('%H:%M:%S', time.localtime(time.time())) > "23:00:00": time.sleep(self.select_refresh_interval)
print "12306休息时间本程序自动停止,明天早上七点运行" if time.strftime('%H:%M:%S', time.localtime(time.time())) > "23:00:00":
print "12306休息时间本程序自动停止,明天早上七点运行"
break
start_time = datetime.datetime.now()
self.submitOrderRequest(from_station, to_station)
print "正在第{0}次查询 乘车日期: {1}, 总耗时{2}ms".format(num, self.station_date, (datetime.datetime.now()-start_time).microseconds/1000)
except PassengerUserException as e:
print e.message
break break
start_time = datetime.datetime.now() except ticketConfigException as e:
self.submitOrderRequest(from_station, to_station) print e.message
print "正在第{0}次查询 乘车日期: {1}, 总耗时{2}ms".format(num, self.station_date, (datetime.datetime.now()-start_time).microseconds/1000) break
except PassengerUserException as e: except ticketIsExitsException as e:
print e.message print e.message
break break
except ticketConfigException as e: except ticketNumOutException as e:
print e.message print e.message
break break
except ticketIsExitsException as e: except ValueError as e:
print e.message if e.message == "No JSON object could be decoded":
break print("12306接口无响应正在重试")
except ticketNumOutException as e: else:
print e.message print(e.message)
break except Exception as e:
except ValueError as e: print e.message
if e.message == "No JSON object could be decoded":
print("12306接口无响应正在重试")
else:
print(e.message)
except Exception as e:
print e.message
if __name__ == '__main__': if __name__ == '__main__':