mirror of https://github.com/testerSunshine/12306
parent
d7c5c7215c
commit
235b0000c9
10
README.md
10
README.md
|
@ -13,7 +13,10 @@
|
|||
- 配置yaml文件的时候,需注意空格和遵循yaml语法格式,项目的yaml配置ex:
|
||||
- ticket_config.yaml 配置说明
|
||||
```
|
||||
#station_date:出发日期,格式ex:2018-01-06
|
||||
#station_date:出发日期改为多日期查询,格式ex:
|
||||
- "2018-02-03"
|
||||
- "2018-02-04"
|
||||
- "2018-02-05"
|
||||
#station_trains:过滤车次,格式ex:
|
||||
# - "G1353"
|
||||
# - "G1329"
|
||||
|
@ -174,6 +177,11 @@
|
|||
- 修复若干bug
|
||||
- 合并dev
|
||||
- 恢复之前因为12306改版引起的订票功能
|
||||
- 增加派对失败自动取消订单功能
|
||||
- 优化接口请求规范
|
||||
- 增加多日期查询,请严格按照yaml格式添加 即可
|
||||
- 注意:如果多日期查询的话,可能查询时间会比较长
|
||||
- 增加如果排队时间超过一分钟,自动取消订单
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -84,5 +84,11 @@ urls = {
|
|||
"initNoCompleteUrl": {
|
||||
"req_url": "https://kyfw.12306.cn/otn/queryOrder/initNoComplete",
|
||||
"req_type": "post"
|
||||
},
|
||||
"cancelNoCompleteMyOrder": {
|
||||
"req_url": "https://kyfw.12306.cn/otn/queryOrder/cancelNoCompleteMyOrder",
|
||||
"req_type": "post"
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -181,7 +181,7 @@ class GoLogin:
|
|||
"""
|
||||
user, passwd = _get_yaml()["set"]["12306count"][0]["uesr"], _get_yaml()["set"]["12306count"][1]["pwd"]
|
||||
if not user or not passwd:
|
||||
raise UserPasswordException("温馨提示: 用户名或者密码为空,请仔细检查!")
|
||||
raise UserPasswordException("温馨提示: 用户名或者密码为空,请仔细检查")
|
||||
login_num = 0
|
||||
while True:
|
||||
self.cookietp()
|
||||
|
|
|
@ -26,7 +26,7 @@ sys.setdefaultencoding('utf-8')
|
|||
|
||||
class select:
|
||||
def __init__(self):
|
||||
self.from_station, self.to_station, self.station_date, self._station_seat, self.is_more_ticket, self.ticke_peoples, self.select_refresh_interval, self.station_trains, self.expect_refresh_interval, self.ticket_black_list_time = self.get_ticket_info()
|
||||
self.from_station, self.to_station, self.station_dates, self._station_seat, self.is_more_ticket, self.ticke_peoples, self.select_refresh_interval, self.station_trains, self.expect_refresh_interval, self.ticket_black_list_time = self.get_ticket_info()
|
||||
self.order_request_params = {} # 订单提交时的参数
|
||||
self.ticketInfoForPassengerForm = {} # 初始化当前页面参数
|
||||
self.current_seats = {} # 席别信息
|
||||
|
@ -47,7 +47,7 @@ class select:
|
|||
ticket_info_config = _get_yaml()
|
||||
from_station = ticket_info_config["set"]["from_station"].encode("utf8")
|
||||
to_station = ticket_info_config["set"]["to_station"].encode("utf8")
|
||||
station_date = ticket_info_config["set"]["station_date"].encode("utf8")
|
||||
station_dates = ticket_info_config["set"]["station_dates"]
|
||||
set_type = ticket_info_config["set"]["set_type"]
|
||||
is_more_ticket = ticket_info_config["set"]["is_more_ticket"]
|
||||
ticke_peoples = ticket_info_config["set"]["ticke_peoples"]
|
||||
|
@ -60,7 +60,7 @@ class select:
|
|||
(
|
||||
from_station,
|
||||
to_station,
|
||||
station_date,
|
||||
station_dates,
|
||||
",".join(set_type),
|
||||
is_more_ticket,
|
||||
",".join(ticke_peoples),
|
||||
|
@ -70,7 +70,7 @@ class select:
|
|||
ticket_black_list_time,
|
||||
)
|
||||
print "*"*20
|
||||
return from_station, to_station, station_date, set_type, is_more_ticket, ticke_peoples, select_refresh_interval, station_trains, expect_refresh_interval, ticket_black_list_time
|
||||
return from_station, to_station, station_dates, set_type, is_more_ticket, ticke_peoples, select_refresh_interval, station_trains, expect_refresh_interval, ticket_black_list_time
|
||||
|
||||
def get_order_request_params(self):
|
||||
return self.order_request_params
|
||||
|
@ -182,7 +182,7 @@ class select:
|
|||
|
||||
def submitOrderRequestFunc(self, from_station, to_station, station_date=None):
|
||||
select_url = self.confUrl["select_url"]["req_url"].format(
|
||||
self.station_date if station_date is None else station_date, from_station, to_station)
|
||||
station_date, from_station, to_station)
|
||||
station_ticket = self.httpClint.send(select_url)
|
||||
return json.loads(station_ticket)
|
||||
|
||||
|
@ -201,44 +201,45 @@ class select:
|
|||
} 参照station_seat()方法
|
||||
:return:
|
||||
"""
|
||||
station_ticket = self.submitOrderRequestFunc(from_station, 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].encode("utf8") == "预订": # 筛选未在开始时间内的车次
|
||||
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 (datetime.datetime.now() - self.ticket_black_list[train_no]).seconds/60 < int(self.ticket_black_list_time):
|
||||
print("该车次{} 正在被关小黑屋,跳过此车次".format(train_no))
|
||||
break
|
||||
else:
|
||||
print ('正在尝试提交订票...')
|
||||
# self.submitOrderRequestFunc(from_station, to_station, self.time())
|
||||
self.submit_station()
|
||||
self.getPassengerTicketStr(self._station_seat[j].encode("utf8"))
|
||||
self.getRepeatSubmitToken()
|
||||
if not self.user_info: # 修改每次都调用用户接口导致用户接口不能用
|
||||
self.user_info = self.getPassengerDTOs()
|
||||
if self.checkOrderInfo(train_no, self._station_seat[j].encode("utf8")):
|
||||
break
|
||||
else:
|
||||
pass
|
||||
else:
|
||||
pass
|
||||
time.sleep(self.expect_refresh_interval)
|
||||
station_tickets = [self.submitOrderRequestFunc(from_station, to_station, station_date) for station_date in self.station_dates]
|
||||
for station_ticket in station_tickets:
|
||||
value = station_ticket['data']
|
||||
if not value:
|
||||
print ('{0}-{1} 车次坐席查询为空...'.format(self.from_station, self.to_station))
|
||||
else:
|
||||
print "车次配置信息有误,或者返回数据异常,请检查 {}".format(station_ticket)
|
||||
if value['result']:
|
||||
for i in value['result']:
|
||||
ticket_info = i.split('|')
|
||||
if ticket_info[11] == "Y" and ticket_info[1].encode("utf8") == "预订": # 筛选未在开始时间内的车次
|
||||
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 (datetime.datetime.now() - self.ticket_black_list[train_no]).seconds/60 < int(self.ticket_black_list_time):
|
||||
print("该车次{} 正在被关小黑屋,跳过此车次".format(train_no))
|
||||
break
|
||||
else:
|
||||
print ('正在尝试提交订票...')
|
||||
# self.submitOrderRequestFunc(from_station, to_station, self.time())
|
||||
self.submit_station()
|
||||
self.getPassengerTicketStr(self._station_seat[j].encode("utf8"))
|
||||
self.getRepeatSubmitToken()
|
||||
if not self.user_info: # 修改每次都调用用户接口导致用户接口不能用
|
||||
self.user_info = self.getPassengerDTOs()
|
||||
if self.checkOrderInfo(train_no, self._station_seat[j].encode("utf8")):
|
||||
break
|
||||
else:
|
||||
pass
|
||||
else:
|
||||
pass
|
||||
time.sleep(self.expect_refresh_interval)
|
||||
else:
|
||||
print "车次配置信息有误,或者返回数据异常,请检查 {}".format(station_ticket)
|
||||
|
||||
def check_user(self):
|
||||
"""
|
||||
|
@ -513,6 +514,9 @@ class select:
|
|||
num += 1
|
||||
if num > 30:
|
||||
print("超出排队时间,自动放弃,正在重新刷票")
|
||||
order_id = self.queryMyOrderNoComplete() # 排队失败,自动取消排队订单
|
||||
if order_id:
|
||||
self.cancelNoCompleteMyOrder(order_id)
|
||||
break
|
||||
try:
|
||||
data = {"random": _random, "tourFlag": "dc"}
|
||||
|
@ -523,8 +527,8 @@ class select:
|
|||
if queryOrderWaitTimeResult:
|
||||
if "status" in queryOrderWaitTimeResult and queryOrderWaitTimeResult["status"]:
|
||||
if "orderId" in queryOrderWaitTimeResult["data"] and queryOrderWaitTimeResult["data"]["orderId"] is not None:
|
||||
sendEmail("恭喜您订票成功,订单号为:{0}, 请立即打开浏览器登录12306,访问‘未完成订单’,在30分钟内完成支付!".format(queryOrderWaitTimeResult["data"]["orderId"]))
|
||||
raise ticketIsExitsException("恭喜您订票成功,订单号为:{0}, 请立即打开浏览器登录12306,访问‘未完成订单’,在30分钟内完成支付!".format(queryOrderWaitTimeResult["data"]["orderId"]))
|
||||
sendEmail("恭喜您订票成功,订单号为:{0}, 请立即打开浏览器登录12306,访问‘未完成订单’,在30分钟内完成支付!".format(queryOrderWaitTimeResult["data"]["orderId"]))
|
||||
raise ticketIsExitsException("恭喜您订票成功,订单号为:{0}, 请立即打开浏览器登录12306,访问‘未完成订单’,在30分钟内完成支付!".format(queryOrderWaitTimeResult["data"]["orderId"]))
|
||||
elif "msg" in queryOrderWaitTimeResult["data"] and queryOrderWaitTimeResult["data"]["msg"]:
|
||||
print queryOrderWaitTimeResult["data"]["msg"]
|
||||
break
|
||||
|
@ -538,11 +542,7 @@ class select:
|
|||
print("第{}次排队中,请耐心等待".format(num))
|
||||
else:
|
||||
print("排队中")
|
||||
time.sleep(1)
|
||||
order_id = self.queryMyOrderNoComplete() # 尝试查看订单列表,如果有订单,则判断成功,不过一般可能性不大
|
||||
if order_id:
|
||||
sendEmail("恭喜您订票成功,订单号为:{0}, 请立即打开浏览器登录12306,访问‘未完成订单’,在30分钟内完成支付!".format(order_id))
|
||||
raise ticketIsExitsException("恭喜您订票成功,订单号为:{0}, 请立即打开浏览器登录12306,访问‘未完成订单’,在30分钟内完成支付!".format(order_id))
|
||||
time.sleep(2)
|
||||
|
||||
else:
|
||||
print(ticketNumOutException("订单提交失败!,正在重新刷票"))
|
||||
|
@ -554,7 +554,7 @@ class select:
|
|||
"""
|
||||
self.initNoComplete()
|
||||
queryMyOrderNoCompleteUrl = self.confUrl["queryMyOrderNoCompleteUrl"]["req_url"]
|
||||
data = {"_json_att": None}
|
||||
data = {"_json_att": ""}
|
||||
try:
|
||||
queryMyOrderNoCompleteResult = self.httpClint.send(queryMyOrderNoCompleteUrl, data)
|
||||
except ValueError:
|
||||
|
@ -581,10 +581,31 @@ class select:
|
|||
获取订单前需要进入订单列表页,获取订单列表页session
|
||||
:return:
|
||||
"""
|
||||
self.httpClint.set_cookies(acw_tc="AQAAAEnFJnekLwwAtGHjZZCr79B6dpXk", current_captcha_type="Z")
|
||||
initNoCompleteUrl = self.confUrl["initNoCompleteUrl"]["req_url"]
|
||||
data = {"_json_att": None}
|
||||
data = {"_json_att": ""}
|
||||
self.httpClint.send(initNoCompleteUrl, data)
|
||||
|
||||
def cancelNoCompleteMyOrder(self, sequence_no):
|
||||
"""
|
||||
取消订单
|
||||
:param sequence_no: 订单编号
|
||||
:return:
|
||||
"""
|
||||
cancelNoCompleteMyOrderUrl = self.confUrl["cancelNoCompleteMyOrder"]["req_url"]
|
||||
cancelNoCompleteMyOrderData = {
|
||||
"sequence_no": sequence_no,
|
||||
"cancel_flag": "cancel_order",
|
||||
"_json_att": ""
|
||||
}
|
||||
cancelNoCompleteMyOrderResult = self.httpClint.send(cancelNoCompleteMyOrderUrl, cancelNoCompleteMyOrderData)
|
||||
if "data" in cancelNoCompleteMyOrderResult and "existError" in cancelNoCompleteMyOrderResult["data"] and cancelNoCompleteMyOrderResult["data"]["existError"] == "N":
|
||||
print("排队超时,已为您自动取消订单,订单编号: {0}".format(sequence_no))
|
||||
time.sleep(2)
|
||||
return True
|
||||
else:
|
||||
print("排队超时,取消订单失败, 订单号{0}".format(sequence_no))
|
||||
|
||||
# def call_submit_ticket(self, function_name=None):
|
||||
# """
|
||||
# 订票失败回调方法,默认执行submitOrderRequest()
|
||||
|
@ -598,7 +619,10 @@ class select:
|
|||
# self.submitOrderRequest()
|
||||
|
||||
def call_login(self):
|
||||
"""登录回调方法"""
|
||||
"""
|
||||
登录回调方法
|
||||
:return:
|
||||
"""
|
||||
login = GoLogin(self.httpClint, self.confUrl)
|
||||
login.go_login()
|
||||
|
||||
|
@ -611,7 +635,7 @@ class select:
|
|||
try:
|
||||
num += 1
|
||||
if "user_time" in self.is_check_user and (datetime.datetime.now() - self.is_check_user["user_time"]).seconds/60 > 10:
|
||||
# 十分钟调用一次检查用户是否登录
|
||||
# 十分钟检查一次用户是否登录
|
||||
self.check_user()
|
||||
time.sleep(self.select_refresh_interval)
|
||||
if time.strftime('%H:%M:%S', time.localtime(time.time())) > "23:00:00":
|
||||
|
@ -620,7 +644,7 @@ class select:
|
|||
self.call_login()
|
||||
start_time = datetime.datetime.now()
|
||||
self.submitOrderRequestImplement(from_station, to_station)
|
||||
print "正在第{0}次查询 乘车日期: {1} 车次{2} 查询无票 代理设置 无 总耗时{3}ms".format(num, self.station_date, ",".join(self.station_trains), (datetime.datetime.now()-start_time).microseconds/1000)
|
||||
print "正在第{0}次查询 乘车日期: {1} 车次{2} 查询无票 代理设置 无 总耗时{3}ms".format(num, ",".join(self.station_dates), ",".join(self.station_trains), (datetime.datetime.now()-start_time).microseconds/1000)
|
||||
except PassengerUserException as e:
|
||||
print e.message
|
||||
break
|
||||
|
|
|
@ -57,6 +57,10 @@ class HTTPClient(object):
|
|||
self._s.headers.update(headers)
|
||||
return self
|
||||
|
||||
def resetHeaders(self):
|
||||
self._s.headers.clear()
|
||||
self._s.headers.update(self._set_header())
|
||||
|
||||
def getHeadersHost(self):
|
||||
return self._s.headers["Host"]
|
||||
|
||||
|
@ -73,16 +77,30 @@ class HTTPClient(object):
|
|||
|
||||
def send(self, url, data=None, **kwargs):
|
||||
"""send request to url.If response 200,return response, else return None."""
|
||||
method = "post"if data else "get"
|
||||
if data:
|
||||
method = "post"
|
||||
self.setHeaders({"Content-Length": "{0}".format(len(data))})
|
||||
else:
|
||||
method = "get"
|
||||
self.resetHeaders()
|
||||
response = self._s.request(method=method,
|
||||
url=url,
|
||||
data=data,
|
||||
**kwargs)
|
||||
# print "url: {0} 返回码: {1}, 返回码type: {2}".format(url, response.status_code, type(response.status_code))
|
||||
# print "response.content" + response.content
|
||||
try:
|
||||
if not response.content:
|
||||
response = self._s.request(method=method,
|
||||
url=url,
|
||||
data=data,
|
||||
**kwargs)
|
||||
if response.content:
|
||||
return json.loads(response.content) if method == "post" else response.content
|
||||
else:
|
||||
return ""
|
||||
except requests.exceptions.ConnectionError as e:
|
||||
print e.message
|
||||
except ValueError as e:
|
||||
if e.message == "No JSON object could be decoded":
|
||||
print("12306接口无响应,正在重试")
|
||||
|
|
Loading…
Reference in New Issue