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中调用ggplot的三种方法
Apr 08 Python
Python的Django REST框架中的序列化及请求和返回
Apr 11 Python
独特的python循环语句
Nov 20 Python
Python编程使用tkinter模块实现计算器软件完整代码示例
Nov 29 Python
python实现多线程网页下载器
Apr 15 Python
Python使用tkinter库实现文本显示用户输入功能示例
May 30 Python
详解利用OpenCV提取图像中的矩形区域(PPT屏幕等)
Jul 01 Python
分享8点超级有用的Python编程建议(推荐)
Oct 13 Python
Python3的unicode编码转换成中文的问题及解决方案
Dec 10 Python
python中提高pip install速度
Feb 14 Python
python爬虫实现POST request payload形式的请求
Apr 30 Python
OpenCV Python实现图像指定区域裁剪
Mar 12 Python
Python字典和列表性能之间的比较
使用pycharm运行flask应用程序的详细教程
只用Python就可以制作的简单词云
python通过函数名调用函数的几种方法总结
Jun 07 #Python
Python爬虫实战之爬取京东商品数据并实实现数据可视化
Python实现的扫码工具居然这么好用!
Jun 07 #Python
忆童年!用Python实现愤怒的小鸟游戏
You might like
PHP 常用函数库和一些实用小技巧
2009/01/01 PHP
PHP实现的链式队列结构示例
2017/09/15 PHP
PHP获取类私有属性的3种方法
2020/09/10 PHP
用javascript实现分割提取页面所需内容
2007/05/09 Javascript
兼容FireFox 的 js 日历 支持时间的获取
2009/03/04 Javascript
JS获得浏览器版本和操作系统版本的例子
2014/05/13 Javascript
nodejs分页类代码分享
2014/06/17 NodeJs
Flexigrid在IE下不显示数据的有效处理方法
2014/09/04 Javascript
javascript中的Function.prototye.bind
2015/06/25 Javascript
jQuery遮罩层实现方法实例详解(附遮罩层插件)
2015/12/08 Javascript
javascript性能优化之DOM交互操作实例分析
2015/12/12 Javascript
基于JS实现数字+字母+中文的混合排序方法
2016/06/06 Javascript
js判断手机号是否正确并返回的实现代码
2017/01/17 Javascript
浅谈Vue.js 组件中的v-on绑定自定义事件理解
2017/11/17 Javascript
Layui 设置select下拉框自动选中某项的方法
2018/08/14 Javascript
详解webpack2异步加载套路
2018/09/14 Javascript
更强大的vue ssr实现预取数据的方式
2019/07/19 Javascript
[01:07:53]RNG vs VG 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/17 DOTA
Python实现的异步代理爬虫及代理池
2017/03/17 Python
Python3.6简单操作Mysql数据库
2017/09/12 Python
TensorFlow损失函数专题详解
2018/04/26 Python
Python 实现取矩阵的部分列,保存为一个新的矩阵方法
2018/11/14 Python
python实现定时发送qq消息
2019/01/18 Python
Python实现的大数据分析操作系统日志功能示例
2019/02/11 Python
python 求一个列表中所有元素的乘积实例
2019/06/11 Python
利用Python库Scapy解析pcap文件的方法
2019/07/23 Python
简单了解django文件下载方式
2020/02/10 Python
python如何判断IP地址合法性
2020/04/05 Python
通过实例解析python and和or使用方法
2020/11/14 Python
解决Pymongo insert时会自动添加_id的问题
2020/12/05 Python
印度尼西亚手表和包包商店:Urban Icon
2019/12/12 全球购物
幼儿园五一活动方案
2014/02/07 职场文书
英语课前三分钟演讲稿(6篇)
2014/09/13 职场文书
骨干教师事迹材料
2014/12/17 职场文书
导游词之广东佛山(南风古灶)
2019/09/24 职场文书
创业计划书之小型广告公司
2019/10/22 职场文书