直接上代碼
#! usr/bin/env python3
# -*- coding:utf8 -*-
# author : DZG
# 使用命令 python D:\Python\Coding\class201606\tickets\getTicketsPython.py changzhou suzhou 2016-09-17
"""Train tickets query via command-line.
Usage:
tickets [-gdtkz] <from> <to> <date>
Options:
-h,--help 顯示幫助菜單
-g 高鐵
-d 動車
-t 特快
-k 快速
-z 直達(dá)
Example:
tickets beijing shanghai 2016-08-25
"""
import re,requests
from docopt import docopt
from prettytable import PrettyTable
class TrainCollection(object):
# 顯示車次、出發(fā)/到達(dá)站决记、 出發(fā)/到達(dá)時間、歷時、一等坐、二等坐箭窜、軟臥饶氏、硬臥、硬座
header = '車次 出發(fā)/到達(dá)站 出發(fā)/到達(dá)時間 歷時 一等坐 二等坐 軟臥 硬臥 硬座'.split()
def __init__(self, rows):
self.rows = rows
def _get_duration(self, row):
"""
獲取車次運(yùn)行時間
"""
duration = row.get('lishi').replace(':', 'h') + 'm'
if duration.startswith('00'):
return duration[4:]
if duration.startswith('0'):
return duration[1:]
return duration
@property
def trains(self):
for row in self.rows:
train = [
# 車次
row['station_train_code'],
# 出發(fā)打厘、到達(dá)站
'\n'.join([row['from_station_name'], row['to_station_name']]),
# 出發(fā)、到達(dá)時間
'\n'.join([row['start_time'], row['arrive_time']]),
# 歷時
self._get_duration(row),
# 一等坐
row['zy_num'],
# 二等坐
row['ze_num'],
# 軟臥
row['rw_num'],
# 軟坐
row['yw_num'],
# 硬坐
row['yz_num']
]
yield train
def pretty_print(self):
"""
數(shù)據(jù)已經(jīng)獲取到了贺辰,剩下的就是提取我們要的信息并將它顯示出來户盯。
`prettytable`這個庫可以讓我們它像MySQL數(shù)據(jù)庫那樣格式化顯示數(shù)據(jù)。
"""
pt = PrettyTable()
# 設(shè)置每一列的標(biāo)題
pt._set_field_names(self.header)
for train in self.trains:
pt.add_row(train)
print(pt)
def cli():
# 命令行接口
arguments = docopt(__doc__)
stations = getAddressDict()
from_staion = stations.get(arguments['<from>'])
to_station = stations.get(arguments['<to>'])
date = arguments['<date>']
# 構(gòu)建URL
url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.format(
date, from_staion, to_station
)
# 添加verify=False參數(shù)不驗(yàn)證證書
r = requests.get(url, verify=False)
rows = r.json()['data']['datas']
trains = TrainCollection(rows)
trains.pretty_print()
# 獲取全國地質(zhì)編碼
def getAddressDict():
url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.8955'
r = requests.get(url, verify=False)
stations = re.findall(r'([A-Z]+)\|([a-z]+)', r.text)
stations = dict(stations)
stations = dict(zip(stations.values(), stations.keys()))
return stations
if __name__ == '__main__':
cli()