天气接口:
中国天气weather.com
(六天预报)
(实时天气信息)
其中101110101是城市的代码,获得城市代码进入
在搜索框上输入你要需要获得天气的城市,点击查询,即可在地址栏获得相应城市编号,然后替换
返回的实时天气的json:
-
{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"18","WD":"东南风","WS":"1级","SD":"17%","WSE":"1","time":"17:05","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1011","rain":"0"}}
代码:
#!/usr/local/bin/python3
#coding=utf-8
# 实时
# 全天
# 六天
## 英文
##
##&hl=zh-cn 中文
import os, io, sys, re, time, base64, json
import webbrowser, urllib.request
#城市
city_list=[
{'code':"101010100",'name':"北京"},
{'code':"101091001",'name':"邯郸"}
]
#返回dict类型: info_dict = {'image': imgPath, 'message': content}
def getCityWeather_Realtime(cityID):
url=""+str(cityID)+".html"
try:
stdout=urllib.request.urlopen(url)
weatherInfo=stdout.read().decode('utf-8')
#print(weatherInfo)
jsonDatas=json.loads(weatherInfo)
city = jsonDatas["weatherinfo"]["city"] #城市
temp = jsonDatas["weatherinfo"]["temp"] #温度
fx = jsonDatas["weatherinfo"]["WD"] #风向
fl = jsonDatas["weatherinfo"]["WS"] #风力
sd = jsonDatas["weatherinfo"]["SD"] #相对湿度
tm = jsonDatas["weatherinfo"]["time"] #发布时间
content ="#" +city + "#" + " " +temp + "℃ " + fx + \
fl + " " + " 相对湿度" + sd + " " +"发布时间:" +tm
info_dict ={'image':"",'message':content}
except (SyntaxError) as err:
print(">>>> SyntaxError: " + err.args)
except:
print(">>>> OtherError: ")
else:
return info_dict
finally:
None
def main():
for city in city_list:
title ="【实时】"
info_dict =getCityWeather_Realtime(city['code'])
print(title + info_dict['message'])
if __name__ == '__main__':
main()
运行结果:
-
【实时】#北京# 18℃ 东南风1级 相对湿度17% 发布时间:17:05
-
【实时】#邯郸# 21℃ 南风3级 相对湿度19% 发布时间:17:05
阅读(1629) | 评论(0) | 转发(0) |