python实现2014火车票查询代码分享


Posted in Python onJanuary 10, 2014

代码基于Python3.3.3,PyQt5.1.1

# -*- coding: utf-8 -*-
# Python 3.3.3
# PyQt 5.1.1
import sys,time,re,urllib.parse,urllib.request,http.cookiejar,json
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
"""cookie"""
cookie=http.cookiejar.LWPCookieJar()
#cookie.load('f:/cookie.txt',True,True)
chandle=urllib.request.HTTPCookieProcessor(cookie)
"""获取数据"""
def getData(url):
    r=urllib.request.Request(url)
    opener=urllib.request.build_opener(chandle)
    u=opener.open(r)
    #chandle.cookiejar.save('f:/cookie.txt',True,True)
    data=u.read()
    try:
        data=data.decode('utf-8')
    except:
        data=data.decode('gbk','ignore')
    return data
def postData(url,data):
    data=urllib.parse.urlencode(data);data=bytes(data,'utf-8')
    r=urllib.request.Request(url,data)
    opener=urllib.request.build_opener(chandle)
    u=opener.open(r)
    #chandle.cookiejar.save('f:/cookie.txt',True,True)
    data=u.read()
    try:
        data=data.decode('utf-8')
    except:
        data=data.decode('gbk','ignore')
    return data
"""火车票"""
class Ticket:
    def init(self,s,e,d):
        self.li=[]
        cont=getData('https://kyfw.12306.cn/otn/resources/js/framework/station_name.js')
        s=re.findall('%s\|([^|]+)' % s,cont)[0]
        e=re.findall('%s\|([^|]+)' % e,cont)[0]
        url='https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=0X00&queryDate=%s&from_station=%s&to_station=%s' % (d,s,e)
        cont=json.loads(getData(url))["data"]["datas"]
        name=[
            "station_train_code",
            "from_station_name",
            "to_station_name",
            "lishi",
            "swz_num",
            "tz_num",
            "zy_num",
            "ze_num",
            "gr_num",
            "rw_num",
            "yw_num",
            "rz_num",
            "yz_num",
            "wz_num",
            "qt_num"
        ]
        for x in cont:
            tmp=[]
            for y in name:
                if y=="from_station_name":
                    s=x[y]+'\n'+x["start_time"]
                    tmp.append(s)
                elif y=="to_station_name":
                    s=x[y]+'\n'+x["arrive_time"]
                    tmp.append(s)
                else:
                    tmp.append(x[y])
            self.li.append(tmp)
"""ui"""
class Dialog(QDialog):
    ticket=Ticket()
    def __init__(self):
        super().__init__()
        self.resize(750,350)
        #布局管理器
        self.layout=[QVBoxLayout(self),QHBoxLayout()]
        self.layout[1].setContentsMargins(0,0,0,0)
        self.layout[1].setSpacing(0)
        self.layout[0].setContentsMargins(0,0,0,0)
        self.layout[0].setSpacing(0)
        self.layout[0].addLayout(self.layout[1])
        #按钮
        btn=QPushButton("ok")
        btn.clicked.connect(self.submit)
        #输入选项
        label=[QLabel("发站:"),QLabel("到站:"),QLabel("日期:")]
        self.line=[QLineEdit(),QLineEdit(),QComboBox()]
        y=int(time.strftime("%Y",time.localtime()))
        m=int(time.strftime("%m",time.localtime()))
        d=int(time.strftime("%d",time.localtime()))
        i=0
        yy=y
        mm=m
        dd=d
        while i<20:
            if m in (1,3,5,7,8,10,12):
                if d+i>31:
                    dd=d+i-31
                    mm=m+1
                    if mm>12:
                        yy=y+1
                        mm=mm-12
                else:
                    dd=d+i
            elif m in (4,6,9,11):
                if d+i>30:
                    dd=d+i-30
                    mm=m+1
                    if mm>12:
                        yy=y+1
                        mm=mm-12
                else:
                    dd=d+i
            else:
                if (m%400==0) or ((m%4==0) and (m%100!=0)):
                    if d+i>29:
                        dd=d+i-29
                        mm=m+1
                        if mm>12:
                            yy=y+1
                            mm=mm-12
                    else:
                        dd=d+i
                else:
                    if d+i>28:
                        dd=d+i-28
                        mm=m+1
                        if mm>12:
                            yy=y+1
                            mm=mm-12
                    else:
                        dd=d+i
            s='%d-%02d-%02d' % (yy,mm,dd)
            self.line[2].addItem(s)
            i+=1
        i=0
        while i<3:
            self.line[i].setMaximumWidth(100)
            label[i].setMaximumWidth(50)
            label[i].setAlignment(Qt.AlignRight|Qt.AlignVCenter)
            self.layout[1].addWidget(label[i],Qt.AlignRight)
            self.layout[1].addWidget(self.line[i],Qt.AlignLeft)
            i+=1
        self.layout[1].addWidget(btn)
        #表格
        head=['车次','发站','到站','历时','商务座','特等座','一等座','二等座','高级软卧','软卧','硬卧','软座','硬座','无座','其他']
        self.table=QTableWidget()
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.table.setColumnCount(15)
        self.table.setHorizontalHeaderLabels(head)
        self.layout[0].addWidget(self.table)
        self.show()
    def submit(self):
        self.table.clearContents()
        s=self.line[0].text()
        e=self.line[1].text()
        d=self.line[2].currentText()
        self.ticket.init(s,e,d)
        self.table.setRowCount(len(self.ticket.li))
        i=0
        for x in self.ticket.li:
            j=0
            for y in x:
                if j==1 or j==2:
                    item=QLabel(y)
                    item.setAlignment(Qt.AlignCenter)
                    self.table.setCellWidget(i,j,item)
                else:
                    item=QTableWidgetItem(y)
                    item.setTextAlignment(Qt.AlignCenter)
                    if not re.search('\D',y):
                        item.setForeground(QBrush(Qt.red))
                    self.table.setItem(i,j,item)
                if j>2 or j==0:
                    self.table.resizeColumnToContents(j)
                j+=1
            i+=1
if __name__=="__main__":
    app=QApplication(sys.argv)
    dialog=Dialog()
    sys.exit(app.exec_())
Python 相关文章推荐
Python实现的简单算术游戏实例
May 26 Python
python list是否包含另一个list所有元素的实例
May 04 Python
对python内置map和six.moves.map的区别详解
Dec 19 Python
python定时按日期备份MySQL数据并压缩
Apr 19 Python
Python 离线工作环境搭建的方法步骤
Jul 29 Python
python批量读取文件名并写入txt文件中
Sep 05 Python
Python3.x+pyqtgraph实现数据可视化教程
Mar 14 Python
python实现音乐播放和下载小程序功能
Apr 26 Python
浅析NumPy 切片和索引
Sep 02 Python
Python pickle模块常用方法代码实例
Oct 10 Python
Python监听键盘和鼠标事件的示例代码
Nov 18 Python
python openssl模块安装及用法
Dec 06 Python
python抓取豆瓣图片并自动保存示例学习
Jan 10 #Python
python文件比较示例分享
Jan 10 #Python
python发送伪造的arp请求
Jan 09 #Python
python抓取京东价格分析京东商品价格走势
Jan 09 #Python
python实现电子词典
Apr 23 #Python
python中cPickle用法例子分享
Jan 03 #Python
使用python获取CPU和内存信息的思路与实现(linux系统)
Jan 03 #Python
You might like
阿拉伯的咖啡与水烟
2021/03/03 咖啡文化
php实现的树形结构数据存取类实例
2014/11/29 PHP
Smarty模板语法详解
2019/07/20 PHP
写出更好的JavaScript程序之undefined篇(中)
2009/11/23 Javascript
jQuery LigerUI 使用教程表格篇(1)
2012/01/18 Javascript
超棒的响应式布局jQuery插件Freetile.js
2014/11/17 Javascript
JavaScript中的值是按值传递还是按引用传递问题探讨
2015/01/30 Javascript
javascript运动详解
2015/07/06 Javascript
canvas实现动态小球重叠效果
2017/02/06 Javascript
jquery.tableSort.js表格排序插件使用方法详解
2020/08/12 Javascript
微信小程序中post方法与get方法的封装
2017/09/26 Javascript
vue 数组和对象不能直接赋值情况和解决方法(推荐)
2017/10/25 Javascript
Angular2学习笔记之数据绑定的示例代码
2018/01/03 Javascript
小程序外卖订单界面的示例代码
2019/12/30 Javascript
[02:46]2014DOTA2国际邀请赛 选手为你解读比赛MVP充满梦想
2014/07/09 DOTA
python计算时间差的方法
2015/05/20 Python
使用Python脚本将文字转换为图片的实例分享
2015/08/29 Python
python遍历目录的方法小结
2016/04/28 Python
Django Web开发中django-debug-toolbar的配置以及使用
2018/05/06 Python
在Pycharm中执行scrapy命令的方法
2019/01/16 Python
Python pandas DataFrame操作的实现代码
2019/06/21 Python
python rsync服务器之间文件夹同步脚本
2019/08/29 Python
python使用pyecharts库画地图数据可视化的实现
2020/03/25 Python
Python 创建TCP服务器的方法
2020/07/28 Python
用python写PDF转换器的实现
2020/10/29 Python
美国肌肉和力量商店:Muscle & Strength
2019/06/22 全球购物
C语言笔试集
2012/07/24 面试题
大学校务公开实施方案
2014/03/31 职场文书
服装仓管员岗位职责
2014/06/17 职场文书
捐款活动总结
2014/08/27 职场文书
前台接待员岗位职责
2015/04/15 职场文书
收入证明范本
2015/06/12 职场文书
企业安全隐患排查治理制度
2015/08/05 职场文书
评奖评优个人先进事迹材料
2015/11/04 职场文书
Win10系统下配置Java环境变量
2021/06/13 Java/Android
Java实战之课程信息管理系统的实现
2022/04/01 Java/Android