目录
一、查询地址
二、解析数据
这里搜索了北京的天气。
找到对应的资源地址(注意其中的地址):
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---------")