1. 程式人生 > >python 12306 車次資料獲取

python 12306 車次資料獲取


ssl._create_default_https_context = ssl._create_default_https_context
train_data = '2018-10-20'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                  ' (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init',
}

data = {
    'leftTicketDTO.train_date': '2018-10-20',
    'leftTicketDTO.from_station': 'ICW',
    'leftTicketDTO.to_station': 'CSQ',
    'urpose_codes': 'ADULT',
}

url = 'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=' \
      '{}&leftTicketDTO.from_station=' \
      'ICW&leftTicketDTO.to_station=CSQ&purpose_codes=ADULT'
url = url.format(train_data)


def get_list():
    # req = requests.Request(url=url, headers=headers, data=data)
    # html = requests.get(req)
    # print(html.json())
    req = request.Request(url)
    req.headers = headers
    # req.data = bytes(data)
    html = urllib.request.urlopen(req)
    print(type(html))
    # print(html.read())
    result = json.load(html)
    for item in result['data']['result']:
        # map = item['result']
        j = 0
        for i in item.split('|'):
            print(j, i)
            j += 1
        # print(item.split('|'))