python 3.6 tkinter+urllib+json 火车车次信息查询

--------blogs:  陈月白    http://www.cnblogs.com/chenyuebai    --------

一、概述

妹子工作时需要大量地查询火车车次至南京的信息,包括该车次到达站(南京站or南京南站)、到达时间、出发时间等,然后根据这些信息做下一步工作。

版本结束,趁着间歇期,帮她弄了个简易的批量查询工具,粉色的按钮是给她用的~哈哈哈! (?*?*?)

大概80行代码,主要是:

界面读取待查询车次 - - - - 调用车次信息接口- - - - 解析返回数据 - - - - 组装结果 - - - - 封装到界面(tkinter)

python+tkinter实现界面,详见之前的学习笔记:http://www.cnblogs.com/chenyuebai/p/7150382.html

最终效果图:

二、实现

1.界面读取待查询车次

之前总结过使用tkinter实现GUI,详见之前的笔记:http://www.cnblogs.com/chenyuebai/p/7150382.html

2.调用车次信息接口

题外话,之前是做的从界面读取待查询车次信息,然后构造成携程的查询url,取到数据后筛选信息;

但后续在取到页面数据后,decode时发现总抛解码异常,百度之,原因是页面源码中编码格式有多样,decode时需要加个错误跳过参数。。

但车次信息恰巧在跳过之列。。。

但是已经跟妹子说很快就能搞好(装b),于是就直接申请了某第三方平台的接口 QAQ

网上查了下,免费的接口基本都不提供服务了。于是用的某第三方平台的接口(某速数据),注册赠1000条,续费5元1W条(暂时没续=。=)

    #调用车次信息接口,获取车次信息
    def getTrainScheduleInfo(self,trainSchedule):
        trainBaseInfo = ""
        #拼接URL
        url = "http://api.xxxx.com/train/line?appkey=xxxxxx&trainno=" + trainSchedule
        #print(url)
        #获取数据
        try:
            trainBaseInfo = self.send_GET_request(url)  #发送GET请求,python3.X是用urllib.request库,网上很多
        except:
            print("ERROR:FUNC getTrainScheduleInfo select_items_from_url failed.url = %s ,flag = %s"%(trainSchedule))
        return trainBaseInfo

3.解析返回数据

返回数据为json类型的字符串,直接json.loads后,解析即可

#获取所有待查询车次信息
        allTrainResultDic = {}      #车次查询结果集合
        for trainSchedule in trainScheduleList:
            trainBaseInfo = self.getTrainScheduleInfo(trainSchedule)        #json string
            # #----测试----
            # trainBaseInfo = ‘‘‘{"status":"0","msg":"ok","result":{"trainno":"G8","type":"高铁","list":[{"sequenceno":"1","station":"上海虹桥","day":"1","arrivaltime":"----","departuretime":"19:00","stoptime":"0","costtime":"0","distance":"0","isend":"0","pricesw":"","pricetd":"","pricegr1":"","pricegr2":"","pricerw1":"0","pricerw2":"0","priceyw1":"0","priceyw2":"0","priceyw3":"0","priceyd":"0.0","priceed":"0.0"},{"sequenceno":"2","station":"南京南","day":"1","arrivaltime":"20:00","departuretime":"20:02","stoptime":"2","costtime":"60","distance":"295","isend":"0","pricesw":"429.5","pricetd":"0","pricegr1":"0","pricegr2":"0","pricerw1":"0","pricerw2":"0","priceyw1":"0","priceyw2":"0","priceyw3":"0","priceyd":"229.5","priceed":"134.5"},{"sequenceno":"3","station":"济南西","day":"1","arrivaltime":"21:59","departuretime":"22:01","stoptime":"2","costtime":"179","distance":"0","isend":"0","pricesw":"1263.5","pricetd":"","pricegr1":"","pricegr2":"","pricerw1":"0","pricerw2":"0","priceyw1":"0","priceyw2":"0","priceyw3":"0","priceyd":"673.5","priceed":"398.5"},{"sequenceno":"4","station":"天津南","day":"1","arrivaltime":"22:59","departuretime":"23:01","stoptime":"2","costtime":"239","distance":"0","isend":"0","pricesw":"1603.5","pricetd":"","pricegr1":"","pricegr2":"","pricerw1":"0","pricerw2":"0","priceyw1":"0","priceyw2":"0","priceyw3":"0","priceyd":"853.5","priceed":"508.5"},{"sequenceno":"5","station":"北京南","day":"1","arrivaltime":"23:34","departuretime":"23:34","stoptime":"0","costtime":"274","distance":"0","isend":"1","pricesw":"1748","pricetd":"","pricegr1":"","pricegr2":"","pricerw1":"0","pricerw2":"0","priceyw1":"0","priceyw2":"0","priceyw3":"0","priceyd":"933.0","priceed":"553.0","costtimetxt":"4时34分"}]}}‘‘‘
            # #----测试----
            print("trainBaseInfo =",trainBaseInfo)
            #解析
            if trainBaseInfo:
                try:
                    trainBaseInfo_loads = json.loads(trainBaseInfo)
                    if trainBaseInfo_loads["status"] == "0":
                        resultNodeValue = trainBaseInfo_loads["result"]
                        trainnoNodeValue = resultNodeValue["trainno"]     #查询车次代码
                        typeNodeValue = resultNodeValue["type"]          #车次类型
                        listNodeValue = resultNodeValue["list"]         #途径站点信息集合 list
                        #筛选出途经南京、南京南
                        for trainInfo in listNodeValue:
                            if (cityName1 in trainInfo.values()) or (cityName2 in trainInfo.values()):
                                #解析数据
                                arrivedStation = trainInfo["station"]         #到达站
                                arrivedTime = trainInfo["arrivaltime"]        #到站时间
                                leaveTime = trainInfo["departuretime"]      #离站时间
                                if arrivedStation == "南京":
                                    arrivedStation = "南京站"
                                # 存储该车次查询结果
                                trainResult = []
                                trainResult.append(arrivedStation)
                                trainResult.append(arrivedTime)
                                trainResult.append(leaveTime)
                                trainResult.append(typeNodeValue)
                                allTrainResultDic[trainSchedule] = trainResult
                            else:
                                #self.write_log_to_Text("ERROR:车次: %s 无途径南京站信息,跳过" % trainSchedule)
                                continue
                    else:
                        self.write_log_to_Text("ERROR:车次: %s 检查返回数据状态码不为0,跳过" % trainSchedule)
                        continue
                except:
                    self.write_log_to_Text("ERROR:车次:%s 返回的json串失败 "% trainSchedule)
            else:
                self.write_log_to_Text("ERROR:车次: %s 查询接口返回信息为空,已跳过"%trainSchedule)
                continue
        print(allTrainResultDic)

4.组装结果、界面输出

        #组装结果界面输出
        self.result_data_Text.delete(1.0, END)
        head = "车次    南京到达站    到站时间    离站时间     类型"
        self.result_data_Text.insert(1.0, head)
        for train in allTrainResultDic.keys():
            outMsg = "\n" + "-" * 52 + "\n" + "%4s"%train + "%9s"%allTrainResultDic[train][0] + "%13s"%allTrainResultDic[train][1] + "%12s"%allTrainResultDic[train][2] + "%8s"%allTrainResultDic[train][3]
            self.result_data_Text.insert(END,outMsg)
        self.write_log_to_Text("INFO:获取火车至南京信息完成")

完成。最终感叹,调接口确实比自己爬省事多了哈哈哈!  ヾ(?°?°?)??

END

2017.12.20

交作业了,妹子很喜欢!nice!

时间: 2024-09-28 18:44:27

python 3.6 tkinter+urllib+json 火车车次信息查询的相关文章

WebApp之JQuery Mobile实现火车列表信息查询

一.项目源代码如下: <!-- --><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>列车时刻表查询</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel=

Android应用源码列车车次与航班信息查询

项目简介:本 项目是一个查询火车车次信息和飞机航班信息的应用源码,可以查询一个城市到另外一个城市的车次和班次的信息,并且可以加入收藏以供日后使用,火车车次信息 和飞机航班信息数据都是由webservice.webxml.com.cn提供,查询出以后可以把车次信息或者航班信息添加到收藏列表,本项目默认编译 版本4.4.2编码GBK有大量中文注释,可以很好的学习和借鉴ListView.SQLite.XmlPullParser的使用方法. 运行截图:

Python GUI with Tkinter (from youtube) 在youtube上能找到很多编程视频...

Python GUI with Tkinter - 1 - Introduction以上链接是一个python tkinter视频系列的第一讲的链接.虽然英语不好,但是,程序还是看得懂的(照着做就可以了),所以找不到中文视频时看下这些英语视频也是可以的. 以下是我在看视频过程中的练习, 可以在python2.7下运行. 001: hello,world: from Tkinter import Label, Tk root = Tk() thelabel = Label(root, text="

python爬虫实例(urllib&BeautifulSoup)

python 2.7.6 urllib:发送报文并得到response BeautifulSoup:解析报文的body(html) #encoding=UTF-8 from bs4 import BeautifulSoup from urllib import urlopen import urllib list_no_results=[]#没查到的银行卡的list list_yes_results=[]#已查到的银行卡的list #解析报文,以字典存储 def parseData(htmls,

python GUI编程(Tkinter)

python GUI编程(Tkinter) python提供了多个图形开发界面的库,几个常用Python GUI库如下: Tkinter: Tkinter模块("Tk 接口")是Python的标准Tk GUI工具包的接口.Tk和Tkinter可以在大多数的Unix平台下使用,同样可以应用在Windows和Macintosh系统里.,Tk8.0的后续版本可以实现本地窗口风格,并良好地运行在绝大多数平台中. wxPython:wxPython 是一款开源软件,是 Python 语言的一套优

python向mysql中存储JSON及Nodejs取出

虽然把JSON数据存入mysql也是比较蛋疼,但是相比使用Nodejs嵌套处理多个mysql查询并拼接返回数据也算是没mongo时的一个折中方案了. 我使用python拼接了一个json格式的字符串,却遇到了一些问题 1,如果把json数据转成str存入,那么nodejs获取数据的时候就无法使用json格式了 处理方法就是 import json data = json.dumps(data_dict, ensure_ascii=False) 通过dumps就可以把python的字典转化成JSO

Python内置的urllib模块不支持https协议的解决办法

Django站点使用django_cas接入SSO(单点登录系统),配置完成后登录,抛出“urlopen error unknown url type: https”异常.寻根朔源发现是python内置的urllib模块不支持https协议. >>> import urllib>>> urllib.urlopen('http://www.baidu.com')<addinfourl at 269231456 whose fp = <socket._fileo

折腾Python中的Tkinter

折腾Python中的Tkinter 从oschina看到了关于Python的Tkinter简介: Tk图形用户界面 Tkinter 又从Python官网文档: Tkinter — Python interface to Tcl/Tk 中,知道了Tkinter是Python内置的. 打算去折腾试试. 1.参考官网的代码,写了下面的: #!/usr/bin/python # -*- coding: utf-8 -*- """ ---------------------------

Python GUI programming(tkinter)

python3之前的版本用Tkinter,之后用的是tkinter 最简单的使用Tkinter的代码,首先要Tk()建立一个窗口,然后加进各种Widget from Tkinter import * window = Tk() label = Label(window, text = "Welcome to Python") button = Button(window, text = "Click me") label.pack() button.pack() w