python 12306 车次数据获取

时间:2023-03-08 16:12:56
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('|'))