python 火车抢票
火车抢票是一件使人烦躁的事情,常常需要反复刷新页面才能够抢到心仪的车票。但是有了Python语言,我们可以用代码来自动完成这项任务,大大提高抢票的成功率。
# 导入必要的库 import requests import json import time # 设置前置参数 from_station = '广州' to_station = '深圳' date = '2021⑴2⑶1' train_no = 'G1001' # 定义函数 def book_ticket(from_station, to_station, date, train_no): # 构造要求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' } # 构造要求URL url = 'https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date=' + date + '&leftTicketDTO.from_station=' + from_station + '&leftTicketDTO.to_station=' + to_station + '&purpose_codes=ADULT' # 发送要求 response = requests.get(url, headers=headers) # 解析响应 all_trains = json.loads(response.text)['data']['result'] for train in all_trains: if train_no in train: ticket_list = train.split('|') if ticket_list[3] == '有' or ticket_list[3] == '有N': print('掌握时机,开始抢票!') return True else: print('当前车次坐位已售空,等待下一班车...') return False # 循环检测可否抢票 while True: if book_ticket(from_station, to_station, date, train_no): print('恭喜你,抢票成功!') break else: print('没法抢到车票,等待下一次检测...') time.sleep(5)
以上就是一个简单的Python火车抢票程序,通过构造要求头和要求URL,发送HTTP要求并解析响应,自动检测车次会不会有票,如果有就尝试抢票。通过循环检测,可让程序一直运行,直到完成抢票任务。
文章来源:丸子建站
文章标题:python 火车抢票
https://www.wanzijz.com/view/77807.html