#模拟浏览器向服务器发送请求
import requests
import re
import urllib.parse #编码
#请求URL,由于该URL请求方式为get
def send_request():
url = 'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2020-08-19&leftTicketDTO.from_station=IZQ&leftTicketDTO.to_station=XMS&purpose_codes=ADULT'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36',
'Cookie': '_uab_collina=159747365464705128119335; JSESSIONID=F6D9AC296707C339E6D146DD6A117C7F; RAIL_DEVICEID=OVFcs8ehj4U3E5U4tYg0O6EpBczEdyW1VGlfjVVGzJ12tjkYPQIyb2R0Xiwe_5YFS8B6_sOzmHW6XUvH1Rn1LFY4WdlhmQA1SXPB1sqhzBU1JoaM3FNhyPt9engE3FFrJw0cTH3ymzmmTsImxnxZ8JtGDjMGVkpR; RAIL_EXPIRATION=1597745363482; _jc_save_fromStation=%u5E7F%u5DDE%u5357%2CIZQ; _jc_save_toStation=%u53A6%u95E8%2CXMS; _jc_save_wfdc_flag=dc; BIGipServerotn=2581004554.24610.0000; BIGipServerpassport=904397066.50215.0000; route=495c805987d0f5c8c84b14f60212447d; _jc_save_fromDate=2020-08-19; _jc_save_toDate=2020-08-18'}
resp = requests.get(url,headers=headers)
resp.encoding='utf-8'
# print(resp.text)
return resp
#提取数据
def parse_json(resp,city):
json_ticket = resp.json() #将响应结果转成json
data_list = json_ticket["data"]["result"] #提取车次的列表
#遍历每一个车次信息
# d = data_list[0].split('|')
lst = []
for item in data_list:
d = item.split('|')
lst.append([d[3],city[d[6]],city[d[7]],d[31],d[30],d[13]])
return lst
'''3、车次
4、车起始
5、车终点
6、查询起始点
7、查询车终点
8、出发时间
9、到达时间
10、历时
21、高级软卧
23、软卧一等座
26、无座
27、软座
28、硬卧二等座
29、硬座
30、二等座、二等包座
31、一等座
32商务特等'''
def start():
lst = parse_json(send_request(),get_city())
for i in lst:
if i[3]!='无'and i[3]!='':
print(i)
#获取站点信息
def get_city():
url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9152'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36'}
resp = requests.get(url,headers=headers)
resp.encoding='utf-8'
stations = re.findall('([\u4e00-\u9fa5]+)\|([A-Z]+)',resp.text) #[\u4e00-\u9fa5]表示全部中文汉字
#将列表转成字典
stations_data = dict(stations)
station_d = {}
for item in stations_data:
station_d[stations_data[item]] = item
return station_d
if __name__ == '__main__':
start()
Python之12306查询
最新推荐文章于 2024-06-17 04:15:06 发布