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天气查询内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • python可视化爬虫界面之天气查询

    执行效果如下: from tkinter import * import urllib.request import gzip import json from tkinter import messagebox root = Tk() def main(): # 输入窗口 root.title('Python学习交流群:973783996') # 窗口标题 Label(root, text='请输入城市').grid(row=0, column=0) # 设置标签并调整位置 enter = E

  • Python实战之制作天气查询软件

    前言 本文主要给大家介绍的是关于Python制作天气查询软件,下面话不多说了,来一起看看详细的介绍吧 效果图 以前,给大家分享了如何使用 PyQt5 制作猜数游戏和计时器,这一次,我们继续学习:如何使用 PyQt5 制作天气查询软件. 源代码和 exe 文件: github 地址:https://github.com/xflywind/Python-Application 本地下载:http://xiazai.jb51.net/201905/yuanma/weather-python(jb51.

  • Python tkinter界面实现历史天气查询的示例代码

    一.实现效果 1. python代码 import requests from lxml import etree import re import tkinter as tk from PIL import Image, ImageTk from xpinyin import Pinyin def get_image(file_nam, width, height): im = Image.open(file_nam).resize((width, height)) return ImageT

  • python小程序基于Jupyter实现天气查询的方法

    天气查询python小程序第0步:导入工具库第一步:生成查询天气的url链接第二步:访问url链接,解析服务器返回的json数据,变成python的字典数据第三步:对字典进行索引,获取气温.风速.风向等天气信息第四步:遍历forecast列表中的五个元素,打印天气信息完整Python代码 本案例是一个非常有趣的python小程序,调用网络API查询指定城市的天气,并打印输出天气信息. 你将学到以下技能: 向网络API发起请求,解析和处理服务器返回的json数据,可以迁移到各种各样的API中,如P

  • Python爬虫+tkinter界面实现历史天气查询的思路详解

    今天给大家分享用Python 爬虫+tkinter界面来实现历史天气查询. 一.实现效果 运行效果 运行效果如下: 二.基本思路 导入用到的库 import requests from lxml import etree import re import tkinter as tk from PIL import Image, ImageTk from xpinyin import Pinyin 1. 爬虫部分 目标url:https://lishi.tianqi.com/ 该网站提供了全国34

  • Python实现天气查询软件

    一.背景 某天下班淋雨成了落汤鸡,发了个朋友圈感慨一下啊,然后...... 夜深人静之时,突然收到了来自学妹的Py文件,运行之后发现事情并不简单(如下图): 这是暗示我...下次出门给她带把伞?不管那么多,作为一个程序猿,遇到程序先拆解一下. 二.工具 爬虫:requests 解析:re UI:tkinter 三.代码解读 想要做一个获取天气预报的小程序,第一步要做的就是能够进行天气预报的爬取,这里通过城市名称匹配百度天气的URL进行爬取,并通过正则的方式进行解析,最终以字典的形式返回结果. c

  • python实现自主查询实时天气

    本文实例为大家分享了python实现自主查询实时天气的具体代码,供大家参考,具体内容如下 用到了urllib2 json  很简单的一个应用 如下 获取城市编号 #coding=utf-8 import urllib2 url1 = 'http://m.weather.com.cn/data3/city.xml' content1 = urllib2.urlopen(url1).read() provinces = content1.split(',') print content1 # 输出c

  • Python脚本制作天气查询实例代码

    获取天气的主要代码如下: # cityCode 替换为具体某一个城市的对应编号 # 1.发送请求,获取数据 url = f'http://wthrcdn.etouch.cn/weather_mini?citykey={cityCode}' res = requests.get(url) res.encoding = 'utf-8' res_json = res.json() # 2.数据格式化 data = res_json['data'] city = f"城市:{data['city']}\

  • python获取天气接口给指定微信好友发天气预报

    先看下效果图: 用到的模块: PyMySQL requests threading wxpy 要实现上面的示例,首先是有两大块地方 获取天气信息 通过微信将天气信息发送出去 而获取天气信息又包括几个小的需要注意的地方 获取天气信息 获取天气信息的接口 获取天气信息的城市 获取所在城市的城市码 假如我们给多个人发送天气情况,这几个人来自不同的城市,那么我们不可能每次都要输入城市名,然后查找城市码,然后再访问接口,获取天气情况,这样会非常的麻烦,所以我们需要考虑将城市名跟城市码一一对应起来,说到一一

  • python通过socket查询whois的方法

    本文实例讲述了python通过socket查询whois的方法.分享给大家供大家参考.具体实现方法如下: import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('whois.networksolutions.com', 43)) s.send('sina.com.cn \r\n') while 1: v = s.recv(1024) if v == '' or v == None: break

  • PHP调用API接口实现天气查询功能的示例

    天气预报查询接口API,在这里我使用的是国家气象局天气预报接口 使用较多的还有:新浪天气预报接口.百度天气预报接口.google天气接口.Yahoo天气接口等等. 1.查询方式 根据地名查询各城市天气情况 2.请求URL地址 http://route.showapi.com/9-2 3.接口参数说明: 一.系统级参数(所有接入点都需要的参数): 二.应用级参数(每个接入点有自己的参数): 4.返回参数 以JSON格式返回结果 1)系统级参数(所有接入点都会返回的参数) 2)应用级参数(系统级输出

随机推荐