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中的二进制位运算符
May 13 Python
python生成excel的实例代码
Nov 08 Python
答题辅助python代码实现
Jan 16 Python
python批量修改文件编码格式的方法
May 31 Python
Django使用paginator插件实现翻页功能的实例
Oct 24 Python
python同时遍历数组的索引和值的实例
Nov 15 Python
Python3 pip3 list 出现 DEPRECATION 警告的解决方法
Feb 16 Python
PyQt使用QPropertyAnimation开发简单动画
Apr 02 Python
sklearn和keras的数据切分与交叉验证的实例详解
Jun 19 Python
python判断字符串以什么结尾的实例方法
Sep 18 Python
python用tkinter实现一个简易能进行随机点名的界面
Sep 27 Python
使用python创建股票的时间序列可视化分析
Mar 03 Python
Python字典和列表性能之间的比较
使用pycharm运行flask应用程序的详细教程
只用Python就可以制作的简单词云
python通过函数名调用函数的几种方法总结
Jun 07 #Python
Python爬虫实战之爬取京东商品数据并实实现数据可视化
Python实现的扫码工具居然这么好用!
Jun 07 #Python
忆童年!用Python实现愤怒的小鸟游戏
You might like
mysql 的 like 问题,超强毕杀记!!!
2007/01/18 PHP
PHP中可以自动分割查询字符的Parse_str函数使用示例
2014/07/25 PHP
php中创建和调用webservice接口示例
2014/07/25 PHP
PHP+jquery实时显示网站在线人数的方法
2015/01/04 PHP
php保存信息到当前Session的方法
2015/03/16 PHP
PHP将Excel导入数据库及数据库数据导出至Excel的方法
2015/06/24 PHP
php错误日志简单配置方法
2016/07/11 PHP
浅谈php中的循环while、do...while、for、foreach四种循环
2016/11/05 PHP
laravel框架上传图片实现实时预览功能
2019/10/14 PHP
php利用ZipArchive类操作文件的实例
2020/01/21 PHP
犀利的js 函数集合
2009/06/11 Javascript
深入认识javascript中的eval函数
2009/11/02 Javascript
JQuery入门——用bind方法绑定事件处理函数应用介绍
2013/02/05 Javascript
javascript html5移动端轻松实现文件上传
2020/03/27 Javascript
谈一谈jQuery核心架构设计
2016/03/28 Javascript
浅谈sass在vue注意的地方
2017/08/10 Javascript
学习LayUI时自研的表单参数校验框架案例分析
2019/07/29 Javascript
layui当点击文本框时弹出选择框,显示选择内容的例子
2019/09/02 Javascript
es6中reduce的基本使用方法
2019/09/10 Javascript
微信浏览器下拉黑边解决方案 wScroollFix
2020/01/21 Javascript
使用python实现递归版汉诺塔示例(汉诺塔递归算法)
2014/04/08 Python
Python实现的Kmeans++算法实例
2014/04/26 Python
详解Python最长公共子串和最长公共子序列的实现
2018/07/07 Python
PyQt5实现类似别踩白块游戏
2019/01/24 Python
Pandas-Cookbook 时间戳处理方式
2019/12/07 Python
django 将自带的数据库sqlite3改成mysql实例
2020/07/09 Python
Python中bisect的用法及示例详解
2020/07/20 Python
python 实现控制鼠标键盘
2020/11/27 Python
《狼》教学反思
2014/03/02 职场文书
鼓舞士气的口号
2014/06/16 职场文书
物业管理专业自荐信
2014/07/01 职场文书
卖房授权委托书样本
2014/10/05 职场文书
优秀工作者事迹材料
2014/12/26 职场文书
经费申请报告范文
2015/05/18 职场文书
利用python做数据拟合详情
2021/11/17 Python
CSS实现鼠标悬浮动画特效
2023/05/07 HTML / CSS