pyqt5-教程系列(十二)PyQt5使用http请求获取天气

作者: haiyang 分类: Python 发布时间: 2019-08-05 11:21

刚才讲了用PyQt5写一个俄罗斯方块的游戏,接下来再说一下如何利用Pyqt5来获取天气预报信息。 这里获取数据是从中国天气官方网址获取。

本案例是采用的获取天气的服务器接口为:
http://wthrcdn.etouch.cn/weather_mini,请求参数名city参数内容为要查询天气的城市名称(utf8字符串)。请求方式为GET

使用QT调用天气接口则需要用到网络类,通过HTTP请求数据。

构造构造图形界面 widget.py 文件

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Widget(object):
    def setupUi(self, Widget):
        Widget.setObjectName("Widget")
        Widget.resize(400, 300)
        self.pushButton = QtWidgets.QPushButton(Widget)
        self.pushButton.setGeometry(QtCore.QRect(300, 40, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.textBrowser = QtWidgets.QTextBrowser(Widget)
        self.textBrowser.setGeometry(QtCore.QRect(20, 10, 256, 161))
        self.textBrowser.setObjectName("textBrowser")
        self.formLayoutWidget = QtWidgets.QWidget(Widget)
        self.formLayoutWidget.setGeometry(QtCore.QRect(50, 179, 160, 111))
        self.formLayoutWidget.setObjectName("formLayoutWidget")
        self.formLayout = QtWidgets.QFormLayout(self.formLayoutWidget)
        self.formLayout.setContentsMargins(11, 11, 11, 11)
        self.formLayout.setSpacing(6)
        self.formLayout.setObjectName("formLayout")
        self.label = QtWidgets.QLabel(self.formLayoutWidget)
        self.label.setObjectName("label")
        self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.label)
        self.lineEdit = QtWidgets.QLineEdit(self.formLayoutWidget)
        self.lineEdit.setObjectName("lineEdit")
        self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.lineEdit)
        self.label_2 = QtWidgets.QLabel(self.formLayoutWidget)
        self.label_2.setObjectName("label_2")
        self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label_2)
        self.lineEdit_2 = QtWidgets.QLineEdit(self.formLayoutWidget)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.lineEdit_2)
        self.label_3 = QtWidgets.QLabel(self.formLayoutWidget)
        self.label_3.setObjectName("label_3")
        self.formLayout.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.label_3)
        self.lineEdit_3 = QtWidgets.QLineEdit(self.formLayoutWidget)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.formLayout.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.lineEdit_3)
        self.label_4 = QtWidgets.QLabel(self.formLayoutWidget)
        self.label_4.setObjectName("label_4")
        self.formLayout.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.label_4)
        self.lineEdit_4 = QtWidgets.QLineEdit(self.formLayoutWidget)
        self.lineEdit_4.setObjectName("lineEdit_4")
        self.formLayout.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.lineEdit_4)

        self.retranslateUi(Widget)
        QtCore.QMetaObject.connectSlotsByName(Widget)

    def retranslateUi(self, Widget):
        _translate = QtCore.QCoreApplication.translate
        Widget.setWindowTitle(_translate("Widget", "Widget"))
        self.pushButton.setText(_translate("Widget", "获取天气"))
        self.label.setText(_translate("Widget", "城市"))
        self.label_2.setText(_translate("Widget", "天气"))
        self.label_3.setText(_translate("Widget", "温度"))
        self.label_4.setText(_translate("Widget", "风力"))

上面的文件是构造构造图形界面。

爬取天气预报信息 weather.py

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtNetwork import *
import widget
import sys

class MyWeather(QWidget):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.mywidget = widget.Ui_Widget()
        self.mywidget.setupUi(self)
        self.manager = QNetworkAccessManager(self)
        self.manager.finished.connect(self.replyFinished)
        self.mywidget.pushButton.clicked.connect(self.request)

    def replyFinished(self, reply):
        str1 = reply.readAll()
        str2 = bytes.decode(str1.data(),encoding='utf8')
        self.mywidget.textBrowser.setText(str2)
        err = QJsonParseError()
        json_recev = QJsonDocument.fromJson(str1,err)
        if not json_recev.isNull():
            myobject = json_recev.object()
            if 'data' in myobject:
                myvalue = myobject['data']
                if myvalue.isObject():
                    myobject_data = myvalue.toObject()
                    if 'forecast' in myobject_data:
                        value = myobject_data['forecast']
                        if value.isArray():
                            value1 = value.toArray()[0].toObject()
                            self.tianqi = value1['type'].toString()
                            self.mywidget.lineEdit_2.setText(self.tianqi)
                            low = value1['low'].toString()
                            high = value1['high'].toString()
                            self.wendu = low[2:] + '-' + high[2:]
                            self.mywidget.lineEdit_3.setText(self.wendu)
                            fengxiang = value1['fengxiang'].toString()
                            fengli = value1['fengli'].toString()
                            self.fengli = fengxiang + fengli[9:-3]
                            self.mywidget.lineEdit_4.setText(self.fengli)



        reply.deleteLater()

    def request(self):
        city = self.mywidget.lineEdit.text() #str
        pre = 'http://wthrcdn.etouch.cn/weather_mini?city='
        res = pre + city
        print(res)
        url = QUrl(res)
        self.manager.get(QNetworkRequest(url))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    weather = MyWeather()
    weather.show()
    sys.exit(app.exec_())

请求天气数据

def request(self):
        city = self.mywidget.lineEdit.text() #str
        pre = 'http://wthrcdn.etouch.cn/weather_mini?city='
        res = pre + city
        print(res)
        url = QUrl(res)
        self.manager.get(QNetworkRequest(url))

回复数据处理槽函数:

def replyFinished(self, reply):
        str1 = reply.readAll()
        str2 = bytes.decode(str1.data(),encoding='utf8')
        self.mywidget.textBrowser.setText(str2)
        err = QJsonParseError()
        json_recev = QJsonDocument.fromJson(str1,err)
        if not json_recev.isNull():
            myobject = json_recev.object()
            if 'data' in myobject:
                myvalue = myobject['data']
                if myvalue.isObject():
                    myobject_data = myvalue.toObject()
                    if 'forecast' in myobject_data:
                        value = myobject_data['forecast']
                        if value.isArray():
                            value1 = value.toArray()[0].toObject()
                            self.tianqi = value1['type'].toString()
                            self.mywidget.lineEdit_2.setText(self.tianqi)
                            low = value1['low'].toString()
                            high = value1['high'].toString()
                            self.wendu = low[2:] + '-' + high[2:]
                            self.mywidget.lineEdit_3.setText(self.wendu)
                            fengxiang = value1['fengxiang'].toString()
                            fengli = value1['fengli'].toString()
                            self.fengli = fengxiang + fengli[9:-3]
                            self.mywidget.lineEdit_4.setText(self.fengli)



        reply.deleteLater()

 天气请求回复的JSON数据中含有多天的详细天气信息,但在此只解析了当天的天气状态、温度和风力三个参数信息,以供参考,Demo程序演示效果如下。

源码地址:
https://github.com/liuyu007/pyQt/tree/master/Desktop/tq

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!

发表评论

电子邮件地址不会被公开。 必填项已用*标注