美文网首页
python php 12306 获取数据

python php 12306 获取数据

作者: 流动码文 | 来源:发表于2017-06-27 17:30 被阅读0次
# coding: utf-8

"""
Usage:
    ticket <from> <to> <date>
    
Options:
    -h, --help 查看帮助
"""

import requests
import re
from docopt import docopt
from prettytable import PrettyTable
from colorama import init, Fore

init()

url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9016'
response = requests.get(url, verify=False)
stations = dict(re.findall(u'([\u4e00-\u9fa5]+)\|([A-Z]+)', response.text))


class TrainsRow:
    header = '车次 车站 时间 历时 一等 二等 软卧 硬卧 硬座 无座'.split()

    def __init__(self, r, station):
        self.trains = r
        self.station = station

    @property
    def get_trains(self):
        trains = self.trains
        trains_show = []
        for train in trains:
            cm = train.split('|')
            cq = {}
            cq['train_no'] = cm[2]
            cq['station_train_code'] = cm[3]
            cq['start_station_telecode'] = cm[4]
            cq['end_station_telecode'] = cm[5]
            cq['from_station_telecode'] = cm[6]
            cq['to_station_telecode'] = cm[7]
            cq['start_time'] = cm[8]
            cq['arrive_time'] = cm[9]
            cq['lishi'] = cm[10]
            cq['canWebBuy'] = cm[11]
            cq['yp_info'] = cm[12]
            cq['start_train_date'] = cm[13]
            cq['train_seat_feature'] = cm[14]
            cq['location_code'] = cm[15]
            cq['from_station_no'] = cm[16]
            cq['to_station_no'] = cm[17]
            cq['is_support_card'] = cm[18]
            cq['controlled_train_flag'] = cm[19]
            cq['gg_num'] = cm[20] and cm[20] or '--'
            cq['gr_num'] = cm[21] and cm[21] or '--'
            cq['qt_num'] = cm[22] and cm[22] or '--'
            cq['rw_num'] = cm[23] and cm[23] or '--'
            cq['rz_num'] = cm[24] and cm[24] or '--'
            cq['tz_num'] = cm[25] and cm[25] or '--'
            cq['wz_num'] = cm[26] and cm[26] or '--'
            cq['yb_num'] = cm[27] and cm[27] or '--'
            cq['yw_num'] = cm[28] and cm[28] or '--'
            cq['yz_num'] = cm[29] and cm[29] or '--'
            cq['ze_num'] = cm[30] and cm[30] or '--'
            cq['zy_num'] = cm[31] and cm[31] or '--'
            cq['swz_num'] = cm[32] and cm[32] or '--'
            cq['srrb_num'] = cm[33] and cm[33] or '--'
            cq['yp_ex'] = cm[34]
            cq['seat_types'] = cm[35]
            trains_show.append(cq)

            train_show = [
                cq['station_train_code'],
                (Fore.RED + self.station[cq['from_station_telecode']] + Fore.RESET),
                cq['start_time'],
                cq['lishi'],
                cq['zy_num'],
                cq['ze_num'],
                cq['rw_num'],
                cq['yw_num'],
                cq['yz_num'],
                cq['wz_num'],
            ]
            train_time_show = [
                '',
                (Fore.GREEN + self.station[cq['to_station_telecode']] + Fore.RESET),
                cq['arrive_time'],
                '',
                '',
                '',
                '',
                '',
                '',
                '',
            ]
            yield train_show
            yield train_time_show

    def pretty_print(self):
        pt = PrettyTable()
        pt._set_field_names(self.header)
        for train in self.get_trains:
            pt.add_row(train)
        print(pt)


def cli():
    arguments = docopt(__doc__)
    date = arguments['<date>']
    from_address = stations.get(arguments['<from>'])
    to_address = 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_address, to_address)

    r = requests.get(url, verify=False)
    result = r.json()['data']['result']
    station = r.json()['data']['map']

    TrainsRow(result, station).pretty_print()


if __name__ == '__main__':
    cli()

python3 ticket.py 大连 北京 2017-07-02 就可以 获取值啦

WechatIMG456.jpeg

下面是php实现该功能的版本

<?php
header("Content-Type: text/html; charset=utf-8");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9035");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$cityText = curl_exec($ch);
curl_close($ch);

preg_match_all('/([\x{4e00}-\x{9fa5}]+)\|([A-Z]+)/u', $cityText, $match);
$citysMap = array();

foreach ($match[0] as $city) {
  $cityMap = explode('|', $city);
  $citysMap[$cityMap[0]] = $cityMap[1];
}

$from = $argv[1];
$to = $argv[2];
$date = $argv[3];

if (array_key_exists($from, $citysMap) && array_key_exists($to, $citysMap)) {
  getData();
} else {
  echo '输入的地址不正确';
}


function getData()
{
  global $date, $from, $to, $citysMap;

  print_r($citysMap);

  $url = "https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={$date}&leftTicketDTO.from_station={$citysMap[$from]}&leftTicketDTO.to_station={$citysMap[$to]}&purpose_codes=ADULT";

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  $data = json_decode(curl_exec($ch))->data->result;
  curl_close($ch);

  handleData($data);
//  print_r($data);
}

function handleData($data)
{
  $dataArray = array();
  foreach ($data as $item) {
    $itemArray = explode('|', $item);

    $data = array();

    $data['train_no'] = $itemArray[2];
    $data['station_train_code'] = $itemArray[3];
    $data['start_station_telecode'] = $itemArray[4];
    $data['end_station_telecode'] = $itemArray[5];
    $data['from_station_telecode'] = $itemArray[6];
    $data['to_station_telecode'] = $itemArray[7];
    $data['start_time'] = $itemArray[8];
    $data['arrive_time'] = $itemArray[9];
    $data['lishi'] = $itemArray[10];
    $data['canWebBuy'] = $itemArray[11];
    $data['yp_info'] = $itemArray[12];
    $data['start_train_date'] = $itemArray[13];
    $data['train_seat_feature'] = $itemArray[14];
    $data['location_code'] = $itemArray[15];
    $data['from_station_no'] = $itemArray[16];
    $data['to_station_no'] = $itemArray[17];
    $data['is_support_card'] = $itemArray[18];
    $data['controlled_train_flag'] = $itemArray[19];
    $data['gg_num'] = $itemArray[20] ? $itemArray[20] : '--';
    $data['gr_num'] = $itemArray[21] ? $itemArray[21] : '--';
    $data['qt_num'] = $itemArray[22] ? $itemArray[22] : '--';
    $data['rw_num'] = $itemArray[23] ? $itemArray[23] : '--';
    $data['rz_num'] = $itemArray[24] ? $itemArray[24] : '--';
    $data['tz_num'] = $itemArray[25] ? $itemArray[25] : '--';
    $data['wz_num'] = $itemArray[26] ? $itemArray[26] : '--';
    $data['yb_num'] = $itemArray[27] ? $itemArray[27] : '--';
    $data['yw_num'] = $itemArray[28] ? $itemArray[28] : '--';
    $data['yz_num'] = $itemArray[29] ? $itemArray[29] : '--';
    $data['ze_num'] = $itemArray[30] ? $itemArray[30] : '--';
    $data['zy_num'] = $itemArray[31] ? $itemArray[31] : '--';
    $data['swz_num'] = $itemArray[32] ? $itemArray[32] : '--';
    $data['srrb_num'] = $itemArray[33] ? $itemArray[33] : '--';
    $data['yp_ex'] = $itemArray[34];
    $data['seat_types'] = $itemArray[35];

    array_push($dataArray, $data);
  }

  print_r($dataArray);
}

相关文章

网友评论

      本文标题:python php 12306 获取数据

      本文链接:https://www.haomeiwen.com/subject/okbecxtx.html