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 相关文章推荐
python3简单实现微信爬虫
Apr 09 Python
Python自动扫雷实现方法
Jul 25 Python
python利用matplotlib库绘制饼图的方法示例
Dec 18 Python
Python数据分析之如何利用pandas查询数据示例代码
Sep 01 Python
解决Python requests库编码 socks5代理的问题
May 07 Python
Python利用scapy实现ARP欺骗的方法
Jul 23 Python
Windows 下更改 jupyterlab 默认启动位置的教程详解
May 18 Python
Django 解决distinct无法去除重复数据的问题
May 20 Python
基于python 取余问题(%)详解
Jun 03 Python
Pycharm创建python文件自动添加日期作者等信息(步骤详解)
Feb 03 Python
Python面向对象之成员相关知识总结
Jun 24 Python
Python爬虫入门案例之回车桌面壁纸网美女图片采集
Oct 16 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
通过curl模拟post和get方式提交的表单类
2014/04/23 PHP
图片完美缩放
2006/09/07 Javascript
SyntaxHighlighter代码加色使用方法
2008/09/07 Javascript
javascript 冒泡排序 正序和倒序实现代码
2010/12/14 Javascript
关闭浏览器窗口弹出提示框并且可以控制其失效
2014/04/15 Javascript
JavaScript中的apply和call函数详解
2014/07/20 Javascript
jQuery动态背景图片效果实现方法
2015/07/03 Javascript
freemarker判断对象是否为空的方法
2015/08/13 Javascript
html5+javascript实现简单上传的注意细节
2016/04/18 Javascript
jQuery height()、innerHeight()、outerHeight()函数的区别详解
2016/05/23 Javascript
jQuery实现iframe父窗体和子窗体的相互调用
2016/06/17 Javascript
最棒的Angular2表格控件
2016/08/10 Javascript
Nodejs下用submit提交表单提示cannot post错误的解决方法
2016/11/21 NodeJs
Angular-Touch库用法示例
2016/12/22 Javascript
Bootstrap源码解读模态弹出框(11)
2016/12/28 Javascript
bootstrap datetimepicker日期插件超详细使用方法介绍
2017/02/23 Javascript
轻量级JS Cookie插件js-cookie的使用方法
2018/03/22 Javascript
vue中post请求以a=a&amp;b=b 的格式写遇到的问题
2018/04/27 Javascript
详解基于Vue2.0实现的移动端弹窗(Alert, Confirm, Toast)组件
2018/08/02 Javascript
用webpack4开发小程序的实现方法
2019/06/04 Javascript
对node通过fs模块判断文件是否是文件夹的实例讲解
2019/06/10 Javascript
微信小程序wx.request拦截器使用详解
2019/07/09 Javascript
Vue表单控件数据绑定方法详解
2020/02/05 Javascript
vue cli4下环境变量和模式示例详解
2020/04/09 Javascript
浅谈es6中的元编程
2020/12/01 Javascript
Ubuntu 14.04+Django 1.7.1+Nginx+uwsgi部署教程
2014/11/18 Python
Python中使用HTMLParser解析html实例
2015/02/08 Python
Python文件处理
2016/02/29 Python
Python读取word文本操作详解
2018/01/22 Python
Python实现找出数组中第2大数字的方法示例
2018/03/26 Python
Python猴子补丁知识点总结
2020/01/05 Python
简单了解python shutil模块原理及使用方法
2020/04/28 Python
最新PyCharm 2020.2.3永久激活码(亲测有效)
2020/11/26 Python
诉讼财产保全担保书
2014/05/20 职场文书
党干部专题民主生活会对照检查材料思想汇报
2014/10/06 职场文书
公司员工离职感言
2015/08/03 职场文书