坚持就是胜利。胜利不重要,重要的是能坚持人生最大的哀痛,是子欲孝而亲不在!人生最大的悲剧,是家未富而人先亡,人生最大的可怜,是弥留之际才明白自己是应该做什么的!
PyQt5+requests实现一个车票查询工具,供大家参考,具体内容如下
结构图
效果图
思路
1、search(QPushButton)点击信号(clicked)连接到自定义的槽函数(event.search)
2、槽函数(event.search)接收四个参数:QTableWidget对象的引用、两个QLabel中的内容(站台名称)、QDateEdit格式化日期
3、槽函数(event.search)调用爬虫类(TrainService)获取车次信息,添加到QTableWidget对象中。
代码
1、ui.py(ui界面)
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'E:\Python\Qt\ui_0.ui' # # Created by: PyQt5 UI code generator 5.11.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets from Event import EventClass class Ui_MainWindow(object): def setupUi(self, MainWindow): event=EventClass() MainWindow.setObjectName("MainWindow") MainWindow.resize(793, 604) MainWindow.setStyleSheet("font: 10pt \"Microsoft YaHei UI\";") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.widget = QtWidgets.QWidget(self.centralwidget) self.widget.setGeometry(QtCore.QRect(0, 0, 791, 43)) self.widget.setObjectName("widget") self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget) self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetNoConstraint) self.horizontalLayout.setContentsMargins(10, 1, 1, 3) self.horizontalLayout.setSpacing(15) self.horizontalLayout.setObjectName("horizontalLayout") self.label = QtWidgets.QLabel(self.widget) self.label.setObjectName("label") self.horizontalLayout.addWidget(self.label) self.lineEdit = QtWidgets.QLineEdit(self.widget) self.lineEdit.setMaximumSize(QtCore.QSize(742, 16777215)) self.lineEdit.setObjectName("lineEdit") self.horizontalLayout.addWidget(self.lineEdit) self.label_2 = QtWidgets.QLabel(self.widget) self.label_2.setObjectName("label_2") self.horizontalLayout.addWidget(self.label_2) self.lineEdit_2 = QtWidgets.QLineEdit(self.widget) self.lineEdit_2.setObjectName("lineEdit_2") self.horizontalLayout.addWidget(self.lineEdit_2) self.dateEdit = QtWidgets.QDateEdit(self.widget) self.dateEdit.setDate(QtCore.QDate(2019, 1, 1)) self.dateEdit.setObjectName("dateEdit") self.horizontalLayout.addWidget(self.dateEdit) self.pushButton = QtWidgets.QPushButton(self.widget) self.pushButton.setObjectName("pushButton") self.horizontalLayout.addWidget(self.pushButton) self.scrollArea = QtWidgets.QScrollArea(self.centralwidget) self.scrollArea.setGeometry(QtCore.QRect(0, 40, 791, 561)) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 789, 559)) self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.tableWidget = QtWidgets.QTableWidget(self.scrollAreaWidgetContents) self.tableWidget.setGeometry(QtCore.QRect(0, 0, 791, 561)) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tableWidget.sizePolicy().hasHeightForWidth()) self.tableWidget.setSizePolicy(sizePolicy) self.tableWidget.setBaseSize(QtCore.QSize(0, 0)) self.tableWidget.setObjectName("tableWidget") self.tableWidget.setColumnCount(5) self.tableWidget.setRowCount(0) item = QtWidgets.QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(1, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(2, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(3, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(4, item) self.tableWidget.horizontalHeader().setDefaultSectionSize(155) self.tableWidget.verticalHeader().setDefaultSectionSize(47) self.tableWidget.verticalHeader().setMinimumSectionSize(45) self.line = QtWidgets.QFrame(self.scrollAreaWidgetContents) self.line.setGeometry(QtCore.QRect(0, 23, 784, 31)) self.line.setToolTipDuration(0) self.line.setLineWidth(1) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") self.scrollArea.setWidget(self.scrollAreaWidgetContents) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.pushButton.clicked.connect(lambda :event.search(self.tableWidget, self.lineEdit.text(), self.lineEdit_2.text(), self.dateEdit.date().toPyDate())) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.label.setText(_translate("MainWindow", "From")) self.label_2.setText(_translate("MainWindow", "To")) self.pushButton.setText(_translate("MainWindow", "search")) item = self.tableWidget.horizontalHeaderItem(0) item.setText(_translate("MainWindow", "车次")) item = self.tableWidget.horizontalHeaderItem(1) item.setText(_translate("MainWindow", "出发时间")) item = self.tableWidget.horizontalHeaderItem(2) item.setText(_translate("MainWindow", "到站时间")) item = self.tableWidget.horizontalHeaderItem(3) item.setText(_translate("MainWindow", "硬卧")) item = self.tableWidget.horizontalHeaderItem(4) item.setText(_translate("MainWindow", "硬座")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
2、EventClass.py(自定义槽函数类)
#coding:u8 import time from PyQt5.QtWidgets import QTableWidgetItem from TrainService import TrainService class EventClass(object): def __init__(self): self.trainService=TrainService() pass def search(self, table, From="北京", To="上海", Date=time.strftime("%Y-%m-%d", time.localtime())): print("【{}】 form {} to {}".format(Date, From, To)) train_list=self.trainService.crawlTrainMess(From, To, Date) print(table) table.setRowCount(len(train_list)) for row, item in enumerate(train_list): for col, i in enumerate(item): if i is "": i="0" table.setItem(row, col, QTableWidgetItem(i)) pass
3、TrainService.py(爬虫类)
#coding_url:u8 import requests import json class TrainService(object): def __init__(self): with open("code.json", 'r') as file: code=eval(file.read()) self.code=code self.code_url="https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9002" self.headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.7 Safari/537.36"} def crawlTrainMess(self,from_station,to_station,train_date): self.url="https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT".format(train_date,self.code[from_station],self.code[to_station]) response=requests.get(self.url,headers=self.headers) train_json=json.loads(response.text) results=train_json['data']['result'] train_list=[] for i in results: temp=i.split('|') train_list.append([temp[3], temp[8], temp[9], temp[25], temp[26]]) #print(train_list) return train_list def crawlCodeMess(self): response=requests.get(self.code_url,headers=self.headers) station_list=response.text.split('@')[1 :] code={} for i in station_list: temp=i.split('|') code[temp[1]]=temp[2] #print(code) with open("code.json", 'w') as file: file.write(str(code)) if __name__=="__main__": ts=TrainService() ts.crawlCodeMess()
需要先跑 TrainService.py 获取到站点对应的代码信息code.json
然后在执行 ui.py
本文PyQt5+requests实现车票查询工具到此结束。有一则谚语说,绵羊每咩咩叫上一次,它就会失掉一口干草,如果你的心态是沉重的,总是抱怨你的苦恼,那么每说一次你便失掉一个快乐的机会。小编再次感谢大家对我们的支持!