def cli(): """command-line interface""" arguments = docopt(__doc__) # print(arguments) from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) # from_station = "上海" # to_station = "北京" date = arguments['<date>'] # url = ('https://kyfw.12306.cn/otn/leftTicket/queryO?' # 'leftTicketDTO.train_date={}&' # 'leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT').format( # date, from_station, to_station # ) # url ="https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2018-06-05&leftTicketDTO.from_station=GZQ&leftTicketDTO.to_station=CSQ&purpose_codes=ADULT" url = ( 'https://kyfw.12306.cn/otn/leftTicket/query?' 'leftTicketDTO.train_date={}&' 'leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT' ).format(date, from_station, to_station) print("====url====" + url) r = requests.get(url, verify=False) # print(r.json()) available_trains = r.json()['data']['result'] available_place = r.json()['data']['map'] options = ''.join( [key for key, value in arguments.items() if value is True]) TrainsCollection(available_trains, available_place, options).pretty_print()
def cli(): """command-line interface""" arguments = docopt(__doc__) from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] # 构建URL url = ('https://kyfw.12306.cn/otn/leftTicket/query?' 'leftTicketDTO.train_date={}&' 'leftTicketDTO.from_station={}&' 'leftTicketDTO.to_station={}&' 'purpose_codes=ADULT').format(date, from_station, to_station) # 选项 options = ''.join([ # 过滤操作 key for key, value in arguments.items() if value is True ]) # 发送请求 r = requests.get(url, verify=True) # 返回数据 trains_data = r.json()['data'] available_trains = trains_data['result'] # 列车车次信息 station_map = trains_data['map'] # 站点中文code映射 # 打印成列表 TrainsCollection(available_trains, station_map, options).pretty_print()
def cli(): """Command-line interface""" arguments = docopt(__doc__) #从stations.py中获得出发地 目的地 from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] """需要修改的地方""" #12306网站上请求和响应时的网址 url = ( 'https://kyfw.12306.cn/otn/leftTicket/queryX?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT' ).format(date, from_station, to_station) #访问请求的格式 headers = { 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Referer': 'https: // kyfw.12306.cn/otn/leftTicket/init', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0', 'X-Requested-With': 'XMLHttpRequest' } options = ''.join( [key for key, value in arguments.items() if value is True]) r = requests.get(url, headers=headers, verify=False) #从网站上请求数据 print(r.json()) available_trains = r.json()['data'] #将数据信息导出 TrainsCollection(available_trains, options).pretty_print() #调用打印函数
def search(): """command-line interface""" arguments = docopt(__doc__) #print(arguments) from_station=stations.get(arguments['<from>']) to_station=stations.get(arguments['<to>']) date=arguments['<date>'] url1='https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2017-04-25&leftTicketDTO.from_station=SHH&leftTicketDTO.to_station=BJP&purpose_codes=ADULT' url2='https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT'.format( date,from_station,to_station ) #python3 train_tickets2.py -g 上海 北京 2017-04-25 注意4要写成04,不要写成2017-4-25 #print (url1) #print (url2) # 这里为什么要加上一个; r = requests.get(url1, verify=False); #print (r.json()) header='车次 起点站 目的站 出发时间 到达时间 历时 一等座 二等座 软卧 硬卧 硬座 无座'.split() pt=PrettyTable() pt._set_field_names(header) if('-d' in arguments.keys()or'-g' in arguments.keys()or'-k' in arguments.keys()or'-t' in arguments.keys()or'-z' in arguments.keys()): print_options(r.json(),pt,arguments) else: print_all(r.json(),pt)
def main(): args = docopt(__doc__) from_station = stations.get(args['<from>']) to_station = stations.get(args['<to>']) date = args['<date>'] if from_station == None: print("From Station is wrong") exit() if to_station == None: print("To Station is wrong") exit() url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.format( date, from_station, to_station ) ret = False while not ret: r = requests.get(url, verify = False) if r.status_code != 200: print("return status is " + str(r.status_code)) continue rows = r.json()["data"]["datas"] ret = parse(rows)
def cli(): """ 命令行接口 """ # 获取文档字符串模板组成的命令行参数字典对象 arguments = docopt(__doc__) from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] # url = ('https://kyfw.12306.cn/otn/leftTicket/queryZ?' # 'leftTicketDTO.train_date={}&' # 'leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT').format( # date, from_station, to_station # ) url = ( 'https://kyfw.12306.cn/otn/leftTicket/queryX?' 'leftTicketDTO.train_date={}&' 'leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT' ).format(date, from_station, to_station) print(url) # 不验证证书 r = requests.get(url, verify=False) available_trains = r.json()['data']['result'] available_place = r.json()['data']['map'] options = ''.join( [key for key, value in arguments.items() if value is True]) TrainsCollection(available_trains, available_place, options).pretty_print()
def cli(): from docopt import docopt from stations import stations import get_data import formats arguments = docopt(__doc__) from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] options = ''.join([ key for key, value in arguments.items() if value is True ]) print 'hehe'; print(options) print 'haha'; print arguments get_data = get_data.GetData(date, from_station, to_station) result = get_data.request_12306() print result #print result if result['httpstatus'] == 200 and result.get('data') is not None and result.get('data') != '': format_result = formats.Formats(result.get('data'), options) return format_result.format_data() else: return result['messages']
def cli(): global L global header arguments = docopt(__doc__) from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36', 'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init' } url = "https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT".format(date,from_station,to_station) r = requests.get(url,verify = False,headers = headers) available_trains = r.json()['data']['result'] for i in range(len(available_trains)): L.append([0]*len(header)) available_trains[i] = re.findall(r'\|[\w\W]+?\|\|[\w\W]+?0',available_trains[i])[0].split('|') for i in range(len(L)): L[i][0] = available_trains[i][2] L[i][1] = get_keys(available_trains[i][4]) L[i][2] = get_keys(available_trains[i][5]) L[i][3] = available_trains[i][8] L[i][4] = available_trains[i][9] L[i][5] = available_trains[i][10] for j in range(6,17): L[i][j] = available_trains[i][len(available_trains[i]) - j + 6 - 3] if available_trains[i][len(available_trains[i]) - j + 6 - 3] != '' else 0 print("正在保存查询结果...") with open('from %s to %s %s.csv' % (arguments['<from>'],arguments['<to>'],arguments['<date>']),'w',newline='') as csvfile: a = csv.writer(csvfile,dialect='excel') a.writerow(header) for i in L: a.writerow(i) print("保存完毕")
def cli(): # """command-line interface""" arguments = docopt(__doc__) # print(arguments) from_station = stations.get( arguments['<from>']) # arguments['<from>'] 是啥鬼?尼玛原来是arguments这个字典相应的值 to_station = stations.get(arguments['<to>']) date = arguments['<date>'] # print('from:', from_station,date,to_station,arguments['<from>'],stations['成都']) url = "https://kyfw.12306.cn/otn/leftTicket/query" querystring = { "leftTicketDTO.train_date": date, "leftTicketDTO.from_station": from_station, "leftTicketDTO.to_station": to_station, "purpose_codes": "ADULT" } options = ''.join( [key for key, value in arguments.items() if value is True]) requests.packages.urllib3.disable_warnings() # 解决Python爬取HTTPS网页时的错误 r = requests.get(url, params=querystring, verify=False) # 添加verify=False参数不验证证书 available_trains = r.json()['data'] # print(available_trains) TrainCollection(available_trains, options).pretty_print()
def clitrainnum(trainnum,from_station,to_station,date): from docopt import docopt from stations import stations import get_data import formats arguments = {'-d': False,'-g': False,'-k': False,'-t': False,'-z': False,'<date>': '2017-03-03','<from>': 'shanghai','<to>': 'beijing'} #arguments = docopt(__doc__) arguments['<from>'] = from_station from_station = stations.get(from_station) arguments['<to>'] = to_station to_station = stations.get(to_station) #date = arguments['<date>'] arguments['<date>'] = date options = ''.join([ key for key, value in arguments.items() if value is True ]) #print(options) print from_station print to_station print date get_data = get_data.GetData(date, from_station, to_station) result = get_data.request_12306() #print result #print result if result['httpstatus'] == 200 and result.get('data') is not None and result.get('data') != '': format_result = formats.Formats(result.get('data'), options); return format_result.trainnumformat_data(trainnum); else: return result['messages']
def cli(): #获取所有参数 args = docopt(__doc__) #始发站 from_station = stations.get(args['<from>']) #终点站 to_station = stations.get(args['<to>']) #日期 date = args['<date>'] #选项 options = ''.join([key for key, value in args.items() if value is True]) #构建url url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.format( date, from_station, to_station) # url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=2016-11-25&from_station=BJP&to_station=SHH' #爬取数据 response = requests.get(url, verify=False) #结果为json类型,转换为字典 response = response.json() #提取datas部分的数据 available_trains = response['data']['datas'] TrainsCollection(available_trains, options).pretty_print()
def find_ticket(self): print('-------------------------') # session.get(url='https://www.12306.cn/index/index.html', headers=headers) self.session.get(url='https://kyfw.12306.cn/otn/leftTicket/init?', headers=self.headers) # self.data = '2019-11-27' # self.fromstation = '合肥' # self.tostation = '上海' self.from_station = stations.get(self.fromstation) self.to_station = stations.get(self.tostation) print('*' * 15 + '余票查询' + '*' * 15) content = cli(self.session, self.data, self.from_station, self.to_station) if self.dev == True: t = re.findall("name='(.*?)', value='(.*?)'", str(self.session.cookies.get_dict)) cook = {li[0]: li[1] for li in t} print('ticket--cookies', end='') print(cook) keys = input('输入需要购买的车次:') if content.get(keys, None): self.secret = content.get(keys, None) print(self.secret) else: print('列车不存在或停运!')
def printTrainInfo(self): arguments = docopt(__doc__) print(arguments['<date>'], arguments['<from>'], arguments['<to>']) date = arguments['<date>'] fromstation = stations.get(arguments['<from>']) tostation = stations.get(arguments['<to>']) url = 'https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date=2018-01-12&leftTicketDTO.from_station=SHH&leftTicketDTO.to_station=HZH&purpose_codes=ADULT'.format( date, fromstation, tostation) r = requests.get(url) print(url) #print(r.json()) #分析12306中返回列车信息数据 allresults = r.json() allTickets = allresults['data']['result'] print(len(allTickets), allTickets) rows = self.parse_train(allTickets) print(rows)
def command(): arguments = docopt(__doc__) #print(arguments) from_sta = stations.get(arguments['<from>']) to_sta = stations.get(arguments['<to>']) date = arguments['<date>'] url = 'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT'.format( date, from_sta, to_sta) resp = requests.get(url, verify=False) #print(resp.json()) options = ''.join( [key for key, value in arguments.items() if value is True]) available_trains = resp.json()['data'] TrainsResult(available_trains, options).pretty_print()
def train_main(self, *args): arguments = docopt(__doc__) try: from_stations = stations.get(arguments['<from>']) dest_stations = stations.get(arguments['<to>']) global date_time date_time = arguments['<date>'] url = 'https://kyfw.12306.cn/otn/leftTicket/queryA?leftTicketDTO.train_date={0}&leftTicketDTO.from_station={1}&leftTicketDTO.to_station={2}&purpose_codes=ADULT'\ .format(date_time,from_stations,dest_stations) #url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT\ #&queryDate={2}&from_station={0}&to_station={1}'\ #.format(from_stations,dest_stations,date_time) except Exception: sys.exit() options = ''.join( [key for key, value in arguments.items() if value is True]) try: r_json = requests.get(url, verify=False) #available_trains = r_json.json()['data']['datas'] available_trains = r_json.json()['data'] TrainsCollection(available_trains, options).pretty_print() except Exception: sys.exit()
def cli(): """解析命令行参数,并且得到车次信息""" arguments = docopt(__doc__) # 通过输入的地点,获取到地点-code from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] # print(from_station,to_station,date) url = 'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT'.format( date, from_station, to_station) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36' } try: # 请求url,并设置不验证 response = requests.get(url, headers=headers, verify=False) response.encoding = 'utf-8' options = ''.join( [key for key, value in arguments.items() if value is True]) # print(options) # print(response.status_code) # 得到我们需要的数据 availabel_trains = response.json()['分析js文件']['result'] # 但是那个格式我们不能直接使用,那么就需要进行把数据格式化一下 availabel_trains = [i.split('|') for i in availabel_trains] # print(availabel_trains) TrickCollection(availabel_trains, options).pretty_print() except: print("查询错误!")
def cli(): arguments = docopt(__doc__) from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] # 构建URL url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.format( date, from_station, to_station)
def cli(): """ commend line interface """ args = docopt(__doc__) # print(args) from_station = args['<from>'] if from_station is None: from_station = '北京' to_station = args['<to>'] if to_station is None: to_station = '上海' date = args['<date>'] now = time.strftime('%Y-%m-%d') if date is None: date = now try: date = time.strptime(date, '%Y-%m-%d') except: print('日期不合法,正确格式:2017-12-12') return if date < time.strptime(now, '%Y-%m-%d'): print('无法查询历史车票信息,请输入今天或之后的时间,默认为今天') return date = time.strftime('%Y-%m-%d', date) #to string print('出发地:{},目的地:{},出发日期:{}'.format( Fore.GREEN + from_station + Fore.RESET, Fore.GREEN + to_station + Fore.RESET, Fore.GREEN + date + Fore.RESET)) url = ('https://kyfw.12306.cn/otn/leftTicket/queryZ?' 'leftTicketDTO.train_date={}&leftTicketDTO.from_station={}' '&leftTicketDTO.to_station={}&purpose_codes=ADULT').format( date, stations.get(from_station), stations.get(to_station)) # print('request url = ', url) requests.packages.urllib3.disable_warnings(InsecureRequestWarning) r = requests.get(url, verify=False) # print('response', r.json()) try: available_trains = r.json()['data']['result'] except: print('没有获取到列车信息') return # 获取参数 options = ''.join([key for key, value in args.items() if value is True]) # print(options) TrainsCollection(available_trains, options).pretty_print()
def click(): """command-line interface""" arguments = docopt(__doc__) # 始发站 # 输入始发站中文,然后在stations里面查询该站代码 from_station_china = arguments['<from>'] if from_station_china in stations: from_station = stations.get(from_station_china) else: print("请输入有效的始发站") return # 终点站 # 输入终点站中文,然后在stations里面查询该站代码 to_station_china = arguments['<to>'] if to_station_china in stations: to_station = stations.get(to_station_china) else: print("请输入有效的终点站") return # 出发时间 date = arguments['<date>'] try: date = date.split('-') date = '%04d-%02d-%02d' % (int(date[0]), int(date[1]), int(date[2])) except: print("请输入有效的时间格式,例如:2018-1-9 或 2018-01-09") return # 构建URL,更换新的接口 url = 'https://kyfw.12306.cn/otn/leftTicket/queryA?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT'\ .format(date, from_station, to_station) # 添加verify=False参数,说明不验证证书 r = requests.get(url, verify=False) try: rows = r.json()['data']['result'] except KeyError: print("请检查接口是否已更新") return except: print("请检查日期是否正确") return # 提取出信息中有用的部分 new_rows = [] for row in rows: split_row = row.split('|') new_rows.append(split_row[1:12] + split_row[13::]) trains = TrainTicket(new_rows) info = ("{}-->{} ({}) 共计{}个车次").format(from_station_china, to_station_china, date, len(new_rows)) print(info) trains.pretty_print()
def cli(): arguments = docopt(__doc__) from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] # 构建URL url = 'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT'.format( date, from_station, to_station )
def getSearchData(arguments): date = arguments['<date>'] from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) url = 'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT'.format( date, from_station, to_station) paramData = {} resultData = getSearchDataByType(url, paramData, type='json') return resultData
def trains(self): for row in self.rows: from_station, to_station = "过", "过" if row[3] == row[5]: from_station = "始" if row[4] == row[6]: to_station = "终" arrive = "当日到达" if row[7].replace(':', '') > row[8].replace(':', ''): arrive = "次日到达" if row[9] == "99:59": arrive = "列车停运" train = [ # 车次 '\n'.join([row[2], row[1]]), # 出发 到达站 '\n'.join([ "\033[0;31;1m" + from_station + "\033[0m" + stations.get(row[5]), "\033[0;34;1m" + to_station + "\033[0m" + stations.get(row[6]) ]), # 出发 到达时间 '\n'.join([ "\033[0;31;1m" + row[7] + "\033[0m", "\033[0;34;1m" + row[8] + "\033[0m" ]), # 历时 '\n'.join([self.__get_duration(row), arrive]), # 商务座 row[-5] if row[-5] else '--', # 一等座 row[-6] if row[-6] else '--', # 二等座 row[-7] if row[-7] else '--', # 高等软卧 row[-16] if row[-16] else '--', # 软卧 row[-14] if row[-14] else '--', # 动卧 row[-4] if row[-4] else '--', # 硬卧 row[-9] if row[-9] else '--', # 软座 row[-13] if row[-13] else '--', # 硬座 row[-8] if row[-8] else '--', # 无座 row[-11] if row[-11] else '--', # 其他 row[-15] if row[-15] else '--', ] # 内置函数,循环遍历 yield train
def __init__(self): # 手机号码 self.phone = '11位手机号码' # 抢票:今天或者明天 self.ticket_get = DAY.OTHER # 指定具体的日期 self.ticket_get_special = '2019-07-10' # 车次 self.bus_no = '车次' # 查询车次的路线id【固定】 self.lineId = '76954' # vehTime:与车次绑定【固定】 self.vehTime = '1745' # 上车地点:** self.onStationId = stations.get('xm1') # 下车地点:** self.offStatinId = stations.get('jwh2') # 用户ID【登录后获取】 self.customerId = '582933' # keycode【登录后获取】 self.keyCode = '5a9312694fba15ed36c6e46df4a63b1e' # 获取验证码 self.code_url = 'http://**/code/phone/login/new?phone={}&t={}&token={}' # 登录 self.login_url = 'http://**/phone/login/new' # 获取车次列表 self.get_bus_url = 'http://**/bc/phone/data?lineNo={}&pageNo=1&pageSize=5&t={}' # 查询余票 # customerId:登录后获取的 self.search_left_ticket_url = 'http://**/bc/phone/surplus/ticket/new?beginDate={}&customerId={}&customerName={}&endDate={}&keyCode={}&lineId={}&t={}&vehTime={}' # 买票 self.buy_ticket_url = 'http://**/order/phone/create?keyCode={}&lineId={}&offStationId={}&onStationId={}&payType=3&saleDates={}&startTime={}&t={}&tradePrice=10&userId={}&userName={}&vehTime={}' self.param_token = '' self.head_token = '' self.login_params = { 'loginCode': '4068', 'loginName': self.phone, 't': '1561427542527' }
def cli(): arguments = docopt(__doc__, version='Tickets 1.0') from_station = stations.get(arguments.get('<from>'), None) to_station = stations.get(arguments.get('<to>'), None) date = arguments.get('<date>') options = ''.join( [key for key, value in arguments.items() if value is True]) url = ('https://kyfw.12306.cn/otn/leftTicket/queryZ?' 'leftTicketDTO.train_date={}&' 'leftTicketDTO.from_station={}&' 'leftTicketDTO.to_station={}&' 'purpose_codes=ADULT').format(date, from_station, to_station) key_list = [] value_list = [] for key, value in stations.items(): key_list.append(key) value_list.append(value) r = requests.get(url) raw_trains = r.json()['data']['result'] pt = PrettyTable() pt._set_field_names('车次 车站 时间 历时 一等 二等 软卧 硬卧 硬座 无座'.split()) for raw_train in raw_trains: data_list = raw_train.split('|') train_no = data_list[3] initial = train_no[0].lower() if not options or initial in options: from_station_code = data_list[6] to_station_code = data_list[7] from_station_index = value_list.index(from_station_code) to_station_index = value_list.index(to_station_code) from_station_name = key_list[from_station_index] to_station_name = key_list[to_station_index] start_time = data_list[8] arrive_time = data_list[9] time_duration = data_list[10] first_class_seat = data_list[31] second_class_seat = data_list[30] soft_sleep = data_list[23] or '--' hard_sleep = data_list[28] or '--' hard_seat = data_list[29] or '--' no_seat = data_list[26] or '--' pt.add_row([ train_no, '\n'.join([ Fore.GREEN + from_station_name + Fore.RESET, Fore.RED + to_station_name + Fore.RESET ]), '\n'.join([ Fore.GREEN + start_time + Fore.RESET, Fore.RED + arrive_time + Fore.RESET ]), time_duration, first_class_seat, second_class_seat, soft_sleep, hard_sleep, hard_seat, no_seat ]) print(pt)
def cli(): """command-line interface""" arguments = docopt(__doc__) from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.format(date,from_station,to_station) r = requests.get(url,verify=False) rows = r.json()['data']['datas'] trains = TrainCollection(rows) trains.pretty_print()
def cli(): arguments = docopt(__doc__) from_station = stations.get(arguments['<from>']) to_staion = stations.get(arguments['<to>']) date = arguments['<date>'] url = 'https://kyfw.12306.cn/otn/leftTicket/queryX?leftTicketDTO.train_date={}&leftTicketDTO.' \ 'from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT' \ .format(date, from_station, to_staion) response = requests.get(url, verify=False) options = ''.join([key for key, value in arguments.items() if value is True]) TransCollection(response.json()['data'], options).pretty_print()
def cli(): """comman-line interface""" args = docopt(__doc__) from_station = stations.get(args['<from>']) to_station = stations.get(args['<to>']) date = args['<date>'] url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.format(date,from_station,to_station) r = requests.get(url, verify=False) rows = r.json()['data']['datas'] trains = TrainCollection(rows) trains.pretty_print()
def cli(): """command-line interface""" arguments = docopt(__doc__) fromStation = stations.get(arguments['<from>']) toStation = stations.get(arguments['<to>']) date = arguments['<date>'] url ='https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT'.format( date, fromStation, toStation) r = requests.get(url) pt = getTrainsInfo(arguments['<from>'], arguments['<to>'], r.json()) print(pt)
def cli(): """command-line interface""" arguments = docopt(__doc__) print(arguments) from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] # ??URL url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.format( date, from_station, to_station ) r = requests.get(url, verify=False)
def cli(): arguments = docopt(__doc__) from_staion = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] # 构建URL url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.format( date, from_staion, to_station ) print(url) r = requests.get(url, verify=False) print(r.json())
def printTrainInfo(self): arguments = docopt(__doc__) print(arguments['<date>'], arguments['<from>'], arguments['<from>']) date = arguments['<date>'] fromstation = stations.get(arguments['<from>']) tostation = stations.get(arguments['<to>']) url = 'https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT'.format( date, fromstation, tostation) r = requests.get(url) print(url) print(r.json())
def cli(): """command-line interface""" arguments=docopt(__doc__) from_station=stations.get(arguments['<from>']) to_station=stations.get(arguments['<to>']) train_date=arguments['<date>'] url='https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT'.format( train_date,from_station,to_station ) options=''.join([key for key,value in arguments.items() if value is True]) r=requests.get(url,verify=False) available_trains=r.json()['data'] TrainsCollections(available_trains,options).prettyprint()
def cli(): """ command-line interface """ arguments = docopt(__doc__) from_station = stations.get(arguments['<from>']).split('|') to_station = stations.get(arguments['<to>']).split('|') date = arguments['<date>'] url = 'https://kyfw.12306.cn/otn/leftTicket/queryT?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT'.format( date, from_station[0], to_station[0]) r = requests.get(url, verify=False) rows = r.json()['data'] trains = TrainCollection(rows) trains.pretty_print()
def cli(self): arguments = docopt(__doc__) from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] url = 'https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date={}' \ '&leftTicketDTO.from_station={}' \ '&leftTicketDTO.to_station={}' \ '&purpose_codes=ADULT'.format( date, from_station, to_station ) r = requests.get(url, verify=False) rows = r.json()['data']['result'] station_map = r.json()['data']['map'] headers = '车次 车站 时间 历时 商务 一等 二等 软卧 硬卧 软座 硬座 无座'.split() pt = PrettyTable() pt._set_field_names(headers) for row in rows: fields = row.split('|') pretty_row = [] # checi pretty_row.append(fields[3]) # chezhan pretty_row.append(station_map[fields[6]] + '-' + station_map[fields[7]]) # time pretty_row.append(fields[8] + '-' + fields[9]) # duration pretty_row.append(fields[10]) # business pretty_row.append(fields[30]) # first_class pretty_row.append(fields[31]) # second_class pretty_row.append(fields[32]) # ruan wo pretty_row.append(fields[23]) # ruan zuo pretty_row.append(fields[24]) # ying wo pretty_row.append(fields[28]) # ying zuo pretty_row.append(fields[29]) # wuzuo pretty_row.append(fields[26]) pt.add_row(pretty_row) print(pt)
def cli(): """ command-line interface """ arguments = docopt(__doc__) from_station = stations.get(arguments['<from>']).split('|') to_station = stations.get(arguments['<to>']).split('|') date = arguments['<date>'] url = 'https://kyfw.12306.cn/otn/leftTicket/queryT?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT'.format( date, from_station[0], to_station[0] ) r = requests.get(url, verify=False) rows = r.json()['data'] trains = TrainCollection(rows) trains.pretty_print()
def cli(): arguments = docopt(__doc__) print(arguments) # 1.神奇的提取参数并且解析成json from_staion = stations.get(arguments['<from>']) # 2. 能这么提取参数 上面写好的形式 to_station = stations.get(arguments['<to>']) date = arguments["<date>"] # 3. 原来还能这么处理 python 里面的 字符串. url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.format(date, from_staion, to_station) print("请求的url : " + url) r = requests.get(url, verify=False) print(r.json())
def cli(): """command-line interface""" arguments = docopt(__doc__) # print(arguments) from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] # build the URL url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.format(date, from_station, to_station) # add 'verify=False' parameter, do not verify the certificate. r = requests.get(url, verify=False) rows = r.json()['data']['datas'] # print(rows) headers = '车次 车站 时间 历时 商务 一等 二等 软卧 硬卧 软座 硬座 无座'.split() pt = PrettyTable() pt._set_field_names(headers) for row in rows: # pt.add_row() # iooo = 1 row_table = [ # 车次 row.get('station_train_code'), # 车站 '\n'.join([ row.get('from_station_name'), row.get('to_station_name')]), # 时间 '\n'.join([ row.get('start_time'), row.get('arrive_time')]), # 历时 row.get('lishi'), # 商务 row.get('swz_num'), # 一等 row.get('zy_num'), # 二等 row.get('ze_num'), # 软卧 row.get('rw_num'), # 硬卧 row.get('yw_num'), # 软座 row.get('rz_num'), # 硬座 row.get('yz_num'), # 无座 row.get('wz_num') ] pt.add_row(row_table) print(pt)
def cli(): '''command-line interface''' arguments = docopt(__doc__) from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] # 构建URL url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.format(date, from_station, to_station) content = requests.get(url,verify=False).json() data = content['data'] message = data.get('message') if message: raise ValueError(message) rows = data['datas'] trains = TrainCollection(rows) trains.pretty_print()
def parser(self, query): all_parameter = query.split() if all_parameter[0] == "-h": self.error_info = None # 用None来表示是帮助信息而不是出错信息 return False if len(all_parameter) < 3: self.error_info = "参数数量不足" return False tmp = stations.get(all_parameter[0]) if not tmp: self.error_info = "未知起始地" return False self.from_sta = tmp tmp = stations.get(all_parameter[1]) if not tmp: self.error_info = "未知目的地" return False self.to_sta = tmp self.off_time = all_parameter[2] if "-" in self.off_time: time_format = "%Y-%m-%d" elif "/" in self.off_time: time_format = "%Y/%m/%d" else: time_format = "%Y%m%d" try: time_tmp = datetime.strptime(self.off_time, time_format) except ValueError as s: self.error_info = "时间格式错误" return False else: self.off_time = datetime.strftime(time_tmp, "%Y-%m-%d") if len(all_parameter) == 4: if not re.match(r"[KDGZT]\d*", all_parameter[3].upper()): self.error_info = "车次不符合格式" return False self.specific_train = all_parameter[3].upper() return True
def cli(self): """command-line interface""" # 获取 出发站点和目标站点 from_station = stations.get(self.args['<from>']) #出发站点 to_station = stations.get(self.args['<to>']) # 目的站点 leave_time = self._get_leave_time()# 出发时间 url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={0}&from_station={1}&to_station={2}'.format( leave_time,from_station,to_station)# 拼接请求列车信息的Url # 获取列车查询结果 r = requests.get(url,verify=False) traindatas = r.json()['data']['datas'] # 返回的结果,转化成json格式,取出datas,方便后面解析列车信息用 # 解析列车信息 traintypes = self._get_traintype() views = TrainCollection(traindatas,traintypes) views.print_pretty()
def cli(): """Command-line interface""" arguments = docopt(__doc__) from_station = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] url = ('https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={}' '&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT').format( date, from_station, to_station ) options = ''.join([ key for key, value in arguments.items() if value is True ]) r = requests.get(url, verify=False) #print(r.json()) available_trains = r.json()['data']['result'] TrainsCollection(available_trains, options).pretty_print()
def cli(): """command-line interface""" arguments = docopt(__doc__) from_staion = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] # 构建URL url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.format( date, from_staion, to_station) r = requests.get(url, verify =False) rows = r.json()['data']['datas'] headers = '车次 始站 到站 上车时间 到达时间 历时 商务 一等 二等 高级软卧 软卧 硬卧 软座 硬座 无座'.split() keys = 'station_train_code from_station_name to_station_name start_time arrive_time lishi swz_num zy_num ze_num gr_num rw_num yw_num rz_num yz_num wz_num'.split() pt = PrettyTable() pt._set_field_names(headers) for row in rows: # 从row中根据headers过滤信息, 然后调用pt.add_row()添加到表中 info = [row[key] for key in keys] pt.add_row(info) print(pt)
def MainProcess(): print('解析查询指令...') try: arguments = parse_cmd() type_dict = {'A':"ADULT",'S':"0X00"} from_arg = stations.get(arguments['<from>']) to_arg = stations.get(arguments['<to>']) date = arguments['<date>'] obj_day = date.split('-') for time_data in obj_day: if(len(time_data)==1): index = obj_day.index(time_data) obj_day[index] = '0'+time_data date = '-'.join(obj_day) guest_type = type_dict.get(arguments['<type>']) print('确认查票信息:from %s to %s on %s, purpose_code: %s' %(from_arg,to_arg,date,guest_type)) url = 'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes={}'.format(date,from_arg,to_arg,guest_type) r = requests.get(url,verify=False) available_trains = r.json()['data']['result'] maps = r.json()['data']['map'] options = ''.join([key for key, value in arguments.items() if value is True]) TrainsCollection = train_parser(available_trains,options,maps,date) TrainsCollection.pretty_print() except : print("""查票出错,可能出现的问题:\n 1.查票时间距离当前的时间过远,建议在一个月以内\n 2.网络繁忙或网络链接中断\n 3.参数格式出错,通过tickets --help查看正确参数使用\n 4.12306官网根证书已过期,需要重新下载安装根证书""") finally: print("完成")
def cli(): """command-line interface""" arguments = docopt(__doc__) from_staion = stations.get(arguments['<from>']) to_station = stations.get(arguments['<to>']) date = arguments['<date>'] # 构建URL url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.format( date, from_staion, to_station) r = requests.get(url, verify=False) rows = r.json()['data']['datas'] headers = '车次 车站 时间 历时 商务 一等 二等 软卧 硬卧 软座 硬座 无座'.split() pt = PrettyTable() pt._set_field_names(headers) for row in rows: # 从row中根据headers过滤信息, 然后调用pt.add_row()添加到表中 pt.add_row([row.get('station_train_code'), ['始发站:' + row.get('from_station_name'), '终点站:' + row.get('to_station_name')], ['发车时间:' + row.get('start_time'), '到达时间:' + row.get('arrive_time')], row.get('lishi'), row.get('swz_num'), '', '', row.get('rw_num'), row.get('yw_num'), row.get('rz_num'), row.get('yz_num'), row.get('wz_num')]) print(pt)
def getTickets(args): if not args: print 'get info fail!' #: 定义文本输出颜色 init(autoreset=True) headers = '车次 车站 时间 历时 商务 一等 二等 软卧 硬卧 软座 硬座 无座'.split() #: 定义表格样式输出 pt = PrettyTable(headers) pt.align['车次'] = '1' pt.padding_width = 1 # pt.pt._set_field_names(headers) #: print types query_date = getDate(args.get('<date>')) query_from = args.get('<from>').decode('utf-8') query_to = args.get('<to>').decode('utf-8') #: 获取数据 com_url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=%s&from_station=%s&to_station=%s' % (query_date, stations.get(query_from), stations.get(query_to)) #: print com_url results = queryHttpData(com_url) if results and 200 == results.json()['httpstatus']: datas = results.json()['data']['datas'] #: print datas types = getTrainType(args) #: print types for row in createRow(types, datas): pt.add_row(row) print pt else: print 'get info fail!'