12306抢票脚本 python
时间: 2023-09-22 18:15:17 浏览: 271
train_ticket-12306抢票脚本
抢票脚本存在法律风险和道德问题,不建议使用。以下是一个简单的 Python 抢票脚本示例,仅供参考:
```python
import time
import requests
# 车次,从左到右依次为高铁/动车,高级软卧,其他软卧,硬卧,软座,硬座
train = ['G100', 'M11', 'K512', 'Z300', 'A987', 'O789']
# 出发日期
date = '2021-01-01'
# 出发地和目的地
from_station = '北京'
to_station = '上海'
# 乘客姓名和证件号码
passenger_name = '张三'
passenger_id = '123456789012345678'
# 登录后获取的cookie
cookie = 'xxxxxx'
# 请求头
headers = {
'Cookie': cookie,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
}
# 查询余票
def query_ticket():
global train, date, from_station, to_station, headers
url = f'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={date}&leftTicketDTO.from_station={from_station}&leftTicketDTO.to_station={to_station}&purpose_codes=ADULT'
response = requests.get(url, headers=headers)
data = response.json()['data']['result']
for i in data:
info = i.split('|')
if info[3] in train and info[-4] != '无' and info[-4] != '0':
return info
return None
# 提交订单
def submit_order():
global headers
url = 'https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest'
data = {
'secretStr': secret_str,
'train_date': date,
'back_train_date': date,
'tour_flag': 'dc',
'purpose_codes': 'ADULT',
'query_from_station_name': from_station,
'query_to_station_name': to_station,
'undefined': ''
}
response = requests.post(url, headers=headers, data=data)
if response.json()['status']:
return True
return False
# 获取乘客信息
def get_passenger():
global headers
url = 'https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs'
data = {
'_json_att': '',
'REPEAT_SUBMIT_TOKEN': token
}
response = requests.post(url, headers=headers, data=data)
data = response.json()['data']['normal_passengers']
for i in data:
if i['passenger_name'] == passenger_name and i['passenger_id_no'] == passenger_id:
return i['passenger_id_type_code'], i['passenger_id_no'], i['passenger_name'], i['mobile_no']
return None
# 获取令牌和密钥
def get_token():
global headers
url = 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'
response = requests.get(url, headers=headers)
html = response.text
token = html.split("globalRepeatSubmitToken = '")[1].split("'")[0]
key_check_is_change = html.split("key_check_isChange':'")[1].split("'")[0]
return token, key_check_is_change
# 获取座位信息
def get_seat():
global headers, seat_type
url = 'https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount'
data = {
'_json_att': '',
'fromStationTelecode': from_station_code,
'leftTicket': left_ticket,
'purpose_codes': 'ADULT',
'REPEAT_SUBMIT_TOKEN': token,
'seatType': seat_type,
'stationTrainCode': train_code,
'toStationTelecode': to_station_code,
'train_date': date,
'train_location': train_location,
'train_no': train_no,
'trainPassType': 'QB',
'trainStartDate': date
}
response = requests.post(url, headers=headers, data=data)
data = response.json()['data']
if data['ticket'] == '0' or data['countT'] == '0':
return False
return True
# 提交订单信息
def confirm_order():
global headers, passenger_info, seat_type, token, key_check_is_change
url = 'https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue'
data = {
'passengerTicketStr': f'{seat_type},0,1,{passenger_info},N',
'oldPassengerStr': f'{passenger_name},{passenger_id},{passenger_type_code}_',
'randCode': '',
'purpose_codes': 'ADULT',
'key_check_isChange': key_check_is_change,
'leftTicketStr': left_ticket,
'train_location': train_location,
'choose_seats': '',
'seatDetailType': '000',
'whatsSelect': '1',
'roomType': '00',
'dwAll': 'N',
'_json_att': '',
'REPEAT_SUBMIT_TOKEN': token
}
response = requests.post(url, headers=headers, data=data)
if response.json()['data']['submitStatus']:
return True
return False
# 获取车站代码
def get_station_code():
global headers, from_station, to_station, from_station_code, to_station_code
url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9102'
response = requests.get(url, headers=headers)
data = response.text.split('@')
for i in data:
if from_station in i:
from_station_code = i.split('|')[2]
elif to_station in i:
to_station_code = i.split('|')[2]
# 主函数
def main():
global seat_type, train_code, train_no, left_ticket, train_location, passenger_type_code, passenger_info, token, key_check_is_change
while True:
print(f'{time.strftime("%H:%M:%S")} 正在查询余票...')
info = query_ticket()
if info:
print(f'{time.strftime("%H:%M:%S")} 有余票,正在提交订单...')
train_code, _, _, _, _, _, _, train_no, _, _, _, _, _, _, _, _, _, left_ticket, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, train_location, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, seat_type, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, passenger_type_code, passenger_info = info
get_station_code()
token, key_check_is_change = get_token()
if submit_order():
if get_passenger():
if get_seat():
if confirm_order():
print(f'{time.strftime("%H:%M:%S")} 订票成功,请及时支付!')
return
else:
print(f'{time.strftime("%H:%M:%S")} 订票失败,重新提交订单...')
else:
print(f'{time.strftime("%H:%M:%S")} 座位不足,重新提交订单...')
else:
print(f'{time.strftime("%H:%M:%S")} 乘客信息错误,重新提交订单...')
else:
print(f'{time.strftime("%H:%M:%S")} 提交订单失败,重新提交订单...')
else:
print(f'{time.strftime("%H:%M:%S")} 暂无余票,继续查询...')
time.sleep(1)
if __name__ == '__main__':
main()
```
该脚本的使用方式如下:
1. 将代码保存为 `12306.py` 文件;
2. 修改 `train`、`date`、`from_station`、`to_station`、`passenger_name`、`passenger_id`、`cookie` 等变量为实际情况;
3. 在终端中执行 `python 12306.py` 命令启动脚本。
需要注意的是,该脚本仅供学习参考,不得用于商业用途和非法用途。同时,12306 网站反爬虫机制较为严格,如果频繁提交订单会被网站封禁账号。
阅读全文