Python——爬取中国气象台网站的天气信息并用Qt显示

时间:2024-03-30 14:49:11

几个月前写的,写的有点垃圾,大神勿喷。

爬取网站:http://www.nmc.cn/

我写了两个.py文件,分别是getjson.py和weather.py

getjson.py是得到目标网站每个省对应的每个市和每个市的url,大体格式为{“province1”:{“city1”:url,“city2”:url,},“province2”:{“city1”:url,“city2”:url,},},将得到的字典转化为json并写入文件中,这样就不需要一直访问目标网站了。

weather.py就是得到目标城市天气信息并用PyQt5显示出来。

getjson.py:

import urllib.request
import json
from lxml import etree

class get_weather():
    def __init__(self):
        self.province_url = 'http://www.nmc.cn/f/rest/province/'
        self.base_url1 = 'http://www.nmc.cn/f/rest/real/'
        self.pro = {}
        self.province_code = {}
        self.get_provice(self.province_url)
    def open_url(self,url):
        req = urllib.request.Request(url)
        req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.89 Safari/537.36')
        response = urllib.request.urlopen(req)
        html = response
        return html

    def get_city(self,url):
        html = self.open_url(url).read().decode('utf-8')
        target = json.loads(html)
        ls = {}
        for i in target:
            ls[i['city']] = 'http://www.nmc.cn/f/rest/real/' + i['code']
        return ls

    def get_provice(self,url):
        html = self.open_url(url).read().decode('utf-8')
        target = json.loads(html)
        for each in target:
            self.province_code[each['name']] = 'http://www.nmc.cn/f/rest/province/'+ each['code'] #省份:code
        for each in target:
            #每一个省对应所有城市名和城市名代号
            self.pro[each['name']] = self.get_city(self.province_code[each['name']]) #得到每个省对应的每个市
        print(self.pro)


def main():
    w = get_weather()
    print("writing")
    with open('weather.json', 'w') as f:
        json.dump(w.pro,f)
        print("finish")
if __name__ == '__main__':
    main()

weather.py

from PyQt5.QtWidgets import QWidget, QMainWindow, QAction, QVBoxLayout, QLineEdit, QPushButton, QTextEdit, QMessageBox, QApplication
from PyQt5.QtGui import QTextCursor, QIcon
from PyQt5.QtNetwork import QTcpSocket
from PyQt5.QtCore import Qt
from PyQt5 import QtWidgets,QtGui
import sys
import json
import urllib.request

def open_url(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.89 Safari/537.36')
    response = urllib.request.urlopen(req)
    return response

def get_weatherinfo(prov, city):

    html = open_url(pro[prov][city]).read().decode('utf-8')

    target = json.loads(html)

    weather_info = {}
    weather_info['城市'] = city
    weather_info['发布时间'] = target['publish_time']
    weather_info['当前温度'] = str(target['weather']['temperature']) + '℃'
    weather_info['体感温度'] = str(target['weather']['feelst']) + '℃'
    weather_info['天气情况'] = str(target['weather']['info'])
    weather_info['相对湿度'] = str(target['weather']['humidity']) + '%'
    weather_info['降水量'] = str(target['weather']['rain']) + 'mm'
    weather_info['风向'] = str(target['wind']['direct']) + ',' + str(target['wind']['power']) + ',风速' + str(target['wind']['speed']) + 'm/s'
    return weather_info

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.pro = ""
        self.city = ""
    def initUI(self):
        self.setWindowTitle('天气查询系统')
        self.setWindowIcon(QIcon('QQ.ico'))
        self.setGeometry(600,400,400,400)
        self.lay = QVBoxLayout(self)
        self.meun1 = QtWidgets.QComboBox(self)
        self.meun2 = QtWidgets.QComboBox(self)
        self.item = QtWidgets.QTextEdit(self)
        self.item.setReadOnly(True)
        self.item.setStyleSheet('color:green')
        font = QtGui.QFont()
        font.setFamily('微软雅黑')
        font.setWeight(100)
        font.setPointSize(10)
        self.item.setFont(font)
        self.item.move(0,80)
        self.item.resize(400,320)
        self.meun1.resize(400,40)
        self.meun2.move(0,40)
        self.meun2.resize(400,40)
        self.lay.addWidget(self.meun1)
        self.lay.addWidget(self.meun2)
        self.lay.addWidget(self.item)
        for each in pro:
            self.meun1.addItem(each)
        for each in pro[self.meun1.currentText()]:
            self.meun2.addItem(each)
        self.meun1.activated.connect(self.nextmeau)
        self.meun2.activated.connect(self.onAction)
        self.get_info()
    def get_info(self):
        self.item.clear()
        pro = self.meun1.currentText()
        city = self.meun2.currentText()
        try:
            info = get_weatherinfo(pro, city)
        except:
            QMessageBox.information(self,'错误', '查询天气失败')
            return
        for each in info:
            self.item.insertPlainText(each + ':' + info[each] + '\n')
            self.item.moveCursor(QTextCursor.End)
    def nextmeau(self):
        self.meun2.clear()
        for each in pro[self.meun1.currentText()]:
            self.meun2.addItem(each)
        self.get_info()
    def onAction(self):
        self.get_info()

if __name__ == '__main__':
    with open('weather.json', 'r') as f:
        pro = json.load(f)
    app = QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())

QQ.ico:(图标)

Python——爬取中国气象台网站的天气信息并用Qt显示

先运行getjson.py得到各个城市的url,然后在运行weather.py

下面是运行效果图:

Python——爬取中国气象台网站的天气信息并用Qt显示
Python——爬取中国气象台网站的天气信息并用Qt显示