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

代码基于python3.3.3,pyqt5.1.1

代码如下:

# -*- coding: utf-8 -*-# python 3.3.3# pyqt 5.1.1import sys,time,re,urllib.parse,urllib.request,http.cookiejar,jsonfrom 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 datadef 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 i31: 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 i2 or j==0: self.table.resizecolumntocontents(j) j+=1 i+=1if __name__==”__main__”: app=qapplication(sys.argv) dialog=dialog() sys.exit(app.exec_())