Python实现天气查询软件

 更新时间:2021年06月07日 14:55:07   作者:数据山谷  
今天给大家带来一个不是那么实用的小工具-天气查询,文中详细介绍了如何实用Python实现天气查询系统,需要的朋友可以参考下

一、背景

某天下班淋雨成了落汤鸡,发了个朋友圈感慨一下啊,然后......

夜深人静之时,突然收到了来自学妹的Py文件,运行之后发现事情并不简单(如下图):

这是暗示我...下次出门给她带把伞?不管那么多,作为一个程序猿,遇到程序先拆解一下。

二、工具

爬虫:requests

解析:re

UI:tkinter

三、代码解读

想要做一个获取天气预报的小程序,第一步要做的就是能够进行天气预报的爬取,这里通过城市名称匹配百度天气的URL进行爬取,并通过正则的方式进行解析,最终以字典的形式返回结果。

class Weather(object):
    def __init__(self):
        pass
 
    def crawl(self, key):
 
        url = 'http://weathernew.pae.baidu.com/weathernew/pc?query=' + key + '天气&srcid=4982&city_name=' + key + '&province_name=' + key
 
        # 设置请求头
        headers = {
            'user-agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
            'Referer': 'https://googleads.g.doubleclick.net/'
        }
        # 页面HTML
        res = requests.get(url, headers=headers).text
        # 时间
        time = re.search(r'\{\"update_time\":\"(.+?)\"', res).group(1)
        # 天气
        weather = re.search(r'\"weather\"\:\"(.+?)\"', res).group(1)
        weather = weather.encode('utf-8').decode("unicode-escape")
        # 气温
        weather_l = re.search(r'temperature_night\"\:\"(.+?)\"', res).group(1)
        weather_h = re.search(r'temperature_day\"\:\"(.+?)\"', res).group(1)
        # 风力
        wind_now = re.search(r'\"wind_power_day\"\:\"(.+?)\"', res).group(1)
        wind_now = wind_now.encode('utf-8').decode("unicode-escape")
        wind_name = re.search(r'\"wind_direction_day\"\:\"(.+?)\"',
                              res).group(1)
        wind_name = wind_name.encode('utf-8').decode("unicode-escape")
        wind = wind_name + wind_now
        # 贴示
        desc = re.search(r'\"desc\"\:\"(.+?)\"', res).group(1)
        desc = desc.encode('utf-8').decode("unicode-escape")
 
        # 结果生
        dic = {
            '城市': key,
            '更新时间': time,
            '天气': weather,
            '温度': weather_l + '-' + weather_h + '摄氏度',
            '风力': wind,
            '贴示': desc,
        }
        return dic

写好了爬取天气预报的代码之后,下面就可以写一个UI来和输入/爬取的内容进行交互的,写UI的方式大同小异,代码如下:

class Weather_UI(object):
    def __init__(self):
        self.window = Tk()
        self.weather = Weather()
 
        self.window.title(u'天气预报')
        # 设置窗口大小和位置
        self.window.geometry('310x370')
        # 创建一个文本框
        self.result_text0 = Label(self.window, text=u'学长所在城市:\n要写中文呦')
        self.result_text0.place(x=10, y=5, height=130)
        self.result_text0.bind('提示')
 
        self.result_text1 = Text(self.window, background='#ccc')
        self.result_text1.place(x=140, y=10, width=155, height=155)
        self.result_text1.bind("<Key-Return>", self.submit)
 
        # 创建一个按钮
        # 为按钮添加事件
        self.submit_btn = Button(self.window,
                                 text=u'获取天气',
                                 command=self.submit)
        self.submit_btn.place(x=170, y=165, width=70, height=25)
        self.submit_btn2 = Button(self.window, text=u'清空', command=self.clean)
        self.submit_btn2.place(x=250, y=165, width=35, height=25)
 
        # 标题
        self.title_label = Label(self.window, text=u'今日天气:')
        self.title_label.place(x=10, y=165)
 
        # 结果
        self.result_text = Text(self.window, background='#ccc')
        self.result_text.place(x=10, y=190, width=285, height=165)
 
    def submit(self):
        # 从输入框获取用户输入的值
        content = self.result_text1.get(0.0, END).strip().replace("\n", " ")
 
        # 把城市信息传到爬虫函数中
        result = self.weather.crawl(content)
 
        # 将结果显示在窗口中的文本框中
        for k, v in result.items():
            self.result_text.insert(END, k + ':' + v)
            self.result_text.insert(END, '\n')
            self.result_text.insert(END, '\n')
 
    # 清空文本域中的内容
    def clean(self):
        self.result_text1.delete(0.0, END)
        self.result_text.delete(0.0, END)
 
    def run(self):
        self.window.mainloop()

运行结果如下:

四、完整代码

import json
import requests
import re
import tkinter as Tk
from tkinter import Tk, Button, Entry, Label, Text, END
 
 
class Weather(object):
    def __init__(self):
        pass
 
    def crawl(self, key):
 
        url = 'http://weathernew.pae.baidu.com/weathernew/pc?query=' + key + '天气&srcid=4982&city_name=' + key + '&province_name=' + key
 
        # 设置请求头
        headers = {
            'user-agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
            'Referer': 'https://googleads.g.doubleclick.net/'
        }
        # 页面HTML
        res = requests.get(url, headers=headers).text
        # 时间
        time = re.search(r'\{\"update_time\":\"(.+?)\"', res).group(1)
        # 天气
        weather = re.search(r'\"weather\"\:\"(.+?)\"', res).group(1)
        weather = weather.encode('utf-8').decode("unicode-escape")
        # 气温
        weather_l = re.search(r'temperature_night\"\:\"(.+?)\"', res).group(1)
        weather_h = re.search(r'temperature_day\"\:\"(.+?)\"', res).group(1)
        # 风力
        wind_now = re.search(r'\"wind_power_day\"\:\"(.+?)\"', res).group(1)
        wind_now = wind_now.encode('utf-8').decode("unicode-escape")
        wind_name = re.search(r'\"wind_direction_day\"\:\"(.+?)\"',
                              res).group(1)
        wind_name = wind_name.encode('utf-8').decode("unicode-escape")
        wind = wind_name + wind_now
        # 贴示
        desc = re.search(r'\"desc\"\:\"(.+?)\"', res).group(1)
        desc = desc.encode('utf-8').decode("unicode-escape")
 
        # 结果生
        dic = {
            '城市': key,
            '更新时间': time,
            '天气': weather,
            '温度': weather_l + '-' + weather_h + '摄氏度',
            '风力': wind,
            '贴示': desc,
        }
        return dic
 
 
class Weather_UI(object):
    def __init__(self):
        self.window = Tk()
        self.weather = Weather()
 
        self.window.title(u'天气预报')
        # 设置窗口大小和位置
        self.window.geometry('310x370')
        # 创建一个文本框
        self.result_text0 = Label(self.window, text=u'学长所在城市:\n要写中文呦')
        self.result_text0.place(x=10, y=5, height=130)
        self.result_text0.bind('提示')
 
        self.result_text1 = Text(self.window, background='#ccc')
        self.result_text1.place(x=140, y=10, width=155, height=155)
        self.result_text1.bind("<Key-Return>", self.submit)
 
        # 创建一个按钮
        # 为按钮添加事件
        self.submit_btn = Button(self.window,
                                 text=u'获取天气',
                                 command=self.submit)
        self.submit_btn.place(x=170, y=165, width=70, height=25)
        self.submit_btn2 = Button(self.window, text=u'清空', command=self.clean)
        self.submit_btn2.place(x=250, y=165, width=35, height=25)
 
        # 标题
        self.title_label = Label(self.window, text=u'今日天气:')
        self.title_label.place(x=10, y=165)
 
        # 结果
        self.result_text = Text(self.window, background='#ccc')
        self.result_text.place(x=10, y=190, width=285, height=165)
 
    def submit(self):
        # 从输入框获取用户输入的值
        content = self.result_text1.get(0.0, END).strip().replace("\n", " ")
 
        # 把城市信息传到爬虫函数中
        result = self.weather.crawl(content)
 
        # 将结果显示在窗口中的文本框中
        for k, v in result.items():
            self.result_text.insert(END, k + ':' + v)
            self.result_text.insert(END, '\n')
            self.result_text.insert(END, '\n')
 
    # 清空文本域中的内容
    def clean(self):
        self.result_text1.delete(0.0, END)
        self.result_text.delete(0.0, END)
 
    def run(self):
        self.window.mainloop()
 
 
A = Weather_UI()
A.run()

到此这篇关于Python实现天气查询系统的文章就介绍到这了,更多相关Python天气查询内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python字符串的多行输出的实例详解

    python字符串的多行输出的实例详解

    在本篇文章里小编给大家整理的是一篇关于python字符串的多行输出的实例详解内容,有兴趣的朋友们跟着学习下。
    2021-06-06
  • np.where()[0] 和 np.where()[1]的具体使用

    np.where()[0] 和 np.where()[1]的具体使用

    这篇文章主要介绍了np.where()[0] 和 np.where()[1]的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • numpy的sum函数的axis和keepdim参数详解

    numpy的sum函数的axis和keepdim参数详解

    这篇文章主要介绍了numpy的sum函数的axis和keepdim参数详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • Python中qutip用法示例详解

    Python中qutip用法示例详解

    这篇文章主要给大家介绍了关于Python中qutip用法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-10-10
  • 通过代码实例解析Pytest运行流程

    通过代码实例解析Pytest运行流程

    这篇文章主要介绍了通过代码实例解析Pytest运行流程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08
  • 如何用python合并多个有规则命名的nc文件

    如何用python合并多个有规则命名的nc文件

    在地学领域,nc格式的文件可谓随处可见,这种文件可以存储多维数字矩阵,下面这篇文章主要给大家介绍了关于如何用python合并多个有规则命名的nc文件的相关资料,需要的朋友可以参考下
    2022-03-03
  • python使用requests+excel进行接口自动化测试的实现

    python使用requests+excel进行接口自动化测试的实现

    在当今的互联网时代中,接口自动化测试越来越成为软件测试的重要组成部分,本文就来介绍了python使用requests+excel进行接口自动化测试的实现,感兴趣的可以了解一下
    2023-11-11
  • 基于Python实现拆分和合并GIF动态图

    基于Python实现拆分和合并GIF动态图

    这篇文章主要介绍了Python拆分和合并GIF动态图,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • python+opencv实现目标跟踪过程

    python+opencv实现目标跟踪过程

    这篇文章主要介绍了python+opencv实现目标跟踪过程,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • python mysql项目实战及框架搭建过程

    python mysql项目实战及框架搭建过程

    本文给大家分享python mysql项目实战框架搭建过程,通过实例代码给大家讲解python mysql项目实战的相关知识,需要的朋友参考下吧
    2021-06-06

最新评论