python爬虫:获取12306网站火车站对应三字码

三字码说明:

在使用python爬取12306票务信息时,火车站到火车站是使用对应的编码实现的,以下为接口网址:
https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2020-4-28&leftTicketDTO.from_station=BJP&leftTicketDTO.to_station=TJP&purpose_codes=ADULT
其中:BJP为北京站编码;TJP为天津站编码。
这两个信息及时间是可以更换的。

程序说明:

采用交互式程序,用户输入起始站名和时间,自动生成可直接使用的接口链接,直接爬取次链接即可。
在这里插入图片描述

# coding=gbk
import urllib.request as r

# 由于火车站使用三字码,所以我们需要先获取站点对应的三字码
code_url = r"https://kyfw.12306.cn/otn/resources/js/framework/station_name.js"
code_data = r.urlopen(code_url).read().decode('utf-8')
#print(code_data)

# 处理获得的字符串,返回字典类型
def zip_dic(code_data):
    code_data = code_data[20:]
    #print(code_data)
    list_code = code_data.split("|")
    #print(list_code)
    a=1
    b=2
    t1=[]
    t2=[]
    while (a < (len(list_code))):
        t1.append(list_code[a])
        t2.append(list_code[b])
        a = a + 5
        b = b + 5
    dic = dict(zip(t1,t2))
    return dic

code_dic = zip_dic(code_data)
#print(code_dic)

# 定义函数,用户输入起始站终点站和时间,转化为编码做返回
def get_message(code_dic):
    from_station = input("输入起始站:\n")
    to_station = input("输入终点站:\n")
    time = input("输入时间,例如:2020-4-28:\n")
    for key,value in code_dic.items():
        if(key == from_station):
            from_station = value
        if(key == to_station):
            to_station = value
    return from_station,to_station,time

from_station,to_station,time = get_message(code_dic)
#print(from_station,to_station,time)

train_url = "https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT".format(time,from_station,to_station)

print(train_url)
原创文章 5 获赞 4 访问量 850

猜你喜欢

转载自blog.csdn.net/kcyxws/article/details/105823767