使用python实现实时的天气查询

目录

一、查询地址

二、解析数据

三、源码

四、结果


一、查询地址

http://www.nmc.cn/

二、解析数据

  这里搜索了北京的天气。 

找到对应的资源地址(注意其中的地址):

http://www.nmc.cn/rest/weather?stationid=54511&_=1685350188717

同样,搜索天津的天气,找到对应的地址:

http://www.nmc.cn/rest/weather?stationid=54517&_=1685350557339

可以发现每个地区由stationid区别。

数据定位:通过相应的k-v类型获取相应的数据。

注意返回的数据格式,下面使用json提取其中的对应数据。

三、源码

import requests  # 引入http请求库
import json  # json格式转换

while True:
    # 菜单
    print("------------实时天气查询---------",
          "            1: 北 京         ",
          "            2: 天 津          ",
          "            3: 退 出          ",
          sep="\n")
    # 输入城市编号
    area = int(input("选择城市序号:"))
    # 判断
    if area == 1:
        staid = "54511"
    elif area == 2:
        staid = "54517"
    elif area == 3:
        print("退出!")
        exit()
    else:
        print("输入错误!")
        continue
    # 定义请求网站,使用staid转换不同地区
    url = "http://www.nmc.cn/rest/weather?_=1685347855322"
    # 定义网址的参数
    params = {"stationid": staid}
    # 请求响应
    reponse = requests.get(url, params=params)
    # 转换数据格式
    reponse_json = json.loads(reponse.text)
    # 获取需要的数据定位
    reData = reponse_json["data"]
    reDatareal = reData["real"]
    reDatarealcode = reDatareal["station"]
    reDatarealweather = reDatareal["weather"]
    # 打印数据
    print("查询城市:", reDatarealcode["province"], "-", reDatarealcode["city"])
    print("实时温度:", reDatarealweather["temperature"])
    print("体感温度:", reDatarealweather["feelst"])
    print("天   气:", reDatarealweather["info"])
    print("更新时间:", reDatareal["publish_time"])
    print("------------Welcome---------")

四、结果

2e68528e8dc04803aeff2916ce2b1c2c.png

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

℡醒着か醉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值