Python实现天气查询软件


Posted in Python onJune 07, 2021

一、背景

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

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

Python实现天气查询软件

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

二、工具

爬虫: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()

运行结果如下:

Python实现天气查询软件

四、完整代码

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常用的日期时间处理方法示例
Feb 08 Python
详解Python中最难理解的点-装饰器
Apr 03 Python
python 生成器协程运算实例
Sep 04 Python
Django处理文件上传File Uploads的实例
May 28 Python
Python面向对象程序设计构造函数和析构函数用法分析
Apr 12 Python
python使用mitmproxy抓取浏览器请求的方法
Jul 02 Python
对python中UDP,socket的使用详解
Aug 22 Python
使用Python第三方库pygame写个贪吃蛇小游戏
Mar 06 Python
python 读txt文件,按‘,’分割每行数据操作
Jul 05 Python
Python实现简单猜数字游戏
Feb 03 Python
Opencv实现二维直方图的计算及绘制
Jul 21 Python
Django框架中表单的用法
Jun 10 Python
Python字典和列表性能之间的比较
使用pycharm运行flask应用程序的详细教程
只用Python就可以制作的简单词云
python通过函数名调用函数的几种方法总结
Jun 07 #Python
Python爬虫实战之爬取京东商品数据并实实现数据可视化
Python实现的扫码工具居然这么好用!
Jun 07 #Python
忆童年!用Python实现愤怒的小鸟游戏
You might like
把从SQL中取出的数据转化成XMl格式
2006/10/09 PHP
需要使用php模板的朋友必看的很多个顶级PHP模板引擎比较分析
2008/05/26 PHP
php 无法加载mcrypt.dll的解决办法
2013/04/03 PHP
基于PHP输出缓存(output_buffering)的深入理解
2013/06/13 PHP
php 魔术方法详解
2014/11/11 PHP
PHP内存缓存功能memcached示例
2016/10/19 PHP
thinkPHP5框架路由常用知识点汇总
2019/09/15 PHP
yii2.0框架场景的简单使用示例
2020/01/25 PHP
读jQuery之十四 (触发事件核心方法)
2011/08/23 Javascript
javascript中创建对象的几种方法总结
2013/11/01 Javascript
jQuery选择器源码解读(二):select方法
2015/03/31 Javascript
vuejs使用FormData实现ajax上传图片文件
2017/08/08 Javascript
vue.js过滤器+ajax实现事件监听及后台php数据交互实例
2018/05/22 Javascript
vue element-ui之怎么封装一个自己的组件的详解
2019/05/20 Javascript
vue vantUI实现文件(图片、文档、视频、音频)上传(多文件)
2019/10/15 Javascript
使用vue cli4.x搭建vue项目的过程详解
2020/05/08 Javascript
JS变量提升及函数提升实例解析
2020/09/03 Javascript
[02:38]DOTA2亚洲邀请赛小组赛精彩集锦:Wings完美团击溃对手
2017/03/29 DOTA
[18:16]sakonoko 2017年卡尔集锦
2018/02/06 DOTA
python文件读写操作与linux shell变量命令交互执行的方法
2015/01/14 Python
python自动化脚本安装指定版本python环境详解
2017/09/14 Python
Python图像处理实现两幅图像合成一幅图像的方法【测试可用】
2019/01/04 Python
Python求离散序列导数的示例
2019/07/10 Python
Pycharm远程调试原理及具体配置详解
2019/08/08 Python
twilio python自动拨打电话,播放自定义mp3音频的方法
2019/08/08 Python
解决Djang2.0.1中的reverse导入失败的问题
2019/08/16 Python
Django 批量插入数据的实现方法
2020/01/12 Python
python3.8下载及安装步骤详解
2020/01/15 Python
Virtualenv 搭建 Py项目运行环境的教程详解
2020/06/22 Python
Python实现Appium端口检测与释放的实现
2020/12/31 Python
Senreve官网:美国旧金山的奢侈手袋品牌
2019/03/21 全球购物
收银员岗位职责
2014/02/07 职场文书
2014年健康教育实施方案
2014/02/17 职场文书
2015年审计人员工作总结
2015/05/26 职场文书
地雷战观后感
2015/06/09 职场文书
2016年党员公开承诺书范文
2016/03/24 职场文书