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中 logging的使用详解
Oct 25 Python
python: line=f.readlines()消除line中\n的方法
Mar 19 Python
分享Pycharm中一些不为人知的技巧
Apr 03 Python
python:接口间数据传递与调用方法
Dec 17 Python
python flask web服务实现更换默认端口和IP的方法
Jul 26 Python
Python3 操作 MySQL 插入一条数据并返回主键 id的实例
Mar 02 Python
python利用opencv实现SIFT特征提取与匹配
Mar 05 Python
Python GUI编程学习笔记之tkinter中messagebox、filedialog控件用法详解
Mar 30 Python
什么是python的必选参数
Jun 21 Python
Python建造者模式案例运行原理解析
Jun 29 Python
python脚本第一行如何写
Aug 30 Python
python 实现弹球游戏的示例代码
Nov 17 Python
Python字典和列表性能之间的比较
使用pycharm运行flask应用程序的详细教程
只用Python就可以制作的简单词云
python通过函数名调用函数的几种方法总结
Jun 07 #Python
Python爬虫实战之爬取京东商品数据并实实现数据可视化
Python实现的扫码工具居然这么好用!
Jun 07 #Python
忆童年!用Python实现愤怒的小鸟游戏
You might like
用Zend Encode编写开发PHP程序
2006/10/09 PHP
不用mod_rewrite直接用php实现伪静态化页面代码
2008/10/04 PHP
遍历指定目录下的所有目录和文件的php代码
2011/11/27 PHP
php将mysql数据库整库导出生成sql文件的具体实现
2014/01/08 PHP
PHP连接SQLServer2005的方法
2015/01/27 PHP
PHP 二维关联数组根据其中一个字段排序(推荐)
2017/04/04 PHP
js中将具有数字属性名的对象转换为数组
2011/03/06 Javascript
js导航菜单(自写)简单大方
2013/03/28 Javascript
Jquery 获取对象的几种方式介绍
2014/01/17 Javascript
jQuery创建DOM元素实例解析
2015/01/19 Javascript
JavaScript中的立即执行函数表达式介绍
2015/03/15 Javascript
jquery的父、子、兄弟节点查找,节点的子节点循环方法
2016/12/07 Javascript
Javascript自定义事件详解
2017/01/13 Javascript
基于原生js运动方式关键点的总结(推荐)
2017/10/01 Javascript
详解vuex结合localstorage动态监听storage的变化
2018/05/03 Javascript
微信小程序chooseImage的用法(从本地相册选择图片或使用相机拍照)
2018/08/22 Javascript
JavaScript中reduce()的5个基本用法示例
2020/07/19 Javascript
解决基于 keep-alive 的后台多级路由缓存问题
2020/12/23 Javascript
Python实现的基数排序算法原理与用法实例分析
2017/11/23 Python
python模拟菜刀反弹shell绕过限制【推荐】
2019/06/25 Python
Django高级编程之自定义Field实现多语言
2019/07/02 Python
python retrying模块的使用方法详解
2019/09/25 Python
德国大型的家具商店:Pharao24.de
2016/10/02 全球购物
美国最佳在线航班预订网站:LookupFare
2019/03/26 全球购物
会计专业毕业生自我评价
2013/09/25 职场文书
幼儿园优秀教师事迹
2014/02/13 职场文书
雏鹰争章活动总结
2014/05/09 职场文书
廉政教育的心得体会
2014/09/01 职场文书
搞笑的爱情检讨书
2014/10/01 职场文书
2014党的群众路线教育实践活动学习心得体会
2014/10/31 职场文书
会议欢迎词
2015/01/23 职场文书
关于倡议书的范文
2015/04/29 职场文书
教师学习中国梦心得体会
2016/01/05 职场文书
读完《骆驼祥子》的观后感!
2019/07/05 职场文书
Python IO文件管理的具体使用
2022/03/20 Python
win10以太网连接不上怎么办?Win10连接以太网详细教程
2022/04/08 数码科技