12306余票查询(三)——获取余票票价

上一节只能看到相关车次,车次的时间,但是没有很重要的一个信息,票价,这显然是很不合理的。通过分析页面请求情况,可知,车次的票价,都是分开请求的,但是一条请求里,包括了了一个车次的所有票价信息
每个车次都得请求一次票价,肯定要把请求票价封装起来
def get_price(train_no, from_station_no, destinction_no, seat_types, date):
    base_url = "https://kyfw.12306.cn/otn/leftTicket/queryTicketPrice?"
    parmas = {
        "train_no": train_no,
        "from_station_no": from_station_no,
        "to_station_no": destinction_no,
        "seat_types": seat_types,
        "train_date": date
    }
    url = base_url + urlencode(parmas)
    try:
        data = requests.get(url).text
    except Exception as e:
        print("获取票价失败"+"|"+e+"|"+url) 
    data = json.loads(data)
    data_dic = data["data"]
    price_dic = {
        "business_price": "--",
        "first_seat_price": "--",
        "second_seat_price": "--",
        "gjrw_seat_price": "--",
        "rw_seat_price": "--",
        "dw_seat_price": "--",
        "yw_seat_price": "--",
        "rz_seat_price": "--",
        "yz_seat_price": "--",
        "wz_seat_price": "--",
        "qt_seat_price": "--"
    }
    # 商务座票价
    if("A9" in data_dic.keys()):
        price_dic["business_price"] = data_dic["A9"]
    elif("p" in data_dic.keys()):
        price_dic["business_price"] = data_dic["p"]
    # 一等座
    if("M" in data_dic.keys()):
        price_dic["first_seat_price"] = data_dic["M"]
    # 二等座
    if("O" in data_dic.keys()):
        price_dic["second_seat_price"] = data_dic["O"]
    # 高级软卧
    if("A6" in data_dic.keys()):
        price_dic["gjrw_seat_price"] = data_dic["A6"]
    # 软卧
    if("A4" in data_dic.keys()):
        price_dic["rw_seat_price"] = data_dic["A4"]
    # 动卧
    if("F" in data_dic.keys()):
        price_dic["dw_seat_price"] = data_dic["F"]
    # 硬卧
    if("A3" in data_dic.keys()):
        price_dic["yw_seat_price"] = data_dic["A3"]
    # 软座
    if("A2" in data_dic.keys()):
        price_dic["rz_seat_price"] = data_dic["A2"]
    # 硬座
    if("A1" in data_dic.keys()):
        price_dic["yz_seat_price"] = data_dic["A1"]
    # 无座
    if("WZ" in data_dic.keys()):
        price_dic["wz_seat_price"] = data_dic["WZ"]
    return price_dic

跟获取余票信息的请求是非常类似的,分析数据也类似,这里就不多说了
这里的函数参数,已经被我们爬下来存入tickets_info中
下一节讲怎么把获取票价得到的信息与余票信息,对应的结合起来

你可能感兴趣的:(python,爬虫,12306余票查询)