首先需下载中国气象局对照表。
然后是Python代码
#利用中国气象局,查询地方天气
import requests
import json
class qx:
def tq(self,num,y):
#打开编码对应链接
weatherUrl = "http://www.weather.com.cn/data/sk/%s.html"%y
#获取页面返回的json数据
response = requests.get(url=weatherUrl).json()
#获取温度
temp = response['weatherinfo']['temp']
#获取风向
WD = response['weatherinfo']['WD'].encode('raw_unicode_escape').decode("utf-8")
#获取风力
WS = response['weatherinfo']['WS'].encode('raw_unicode_escape').decode("utf-8")
print("当前城市:%s,当前温度:%s,当前风向:%s,当前风力:%s"%(num,temp,WD,WS))
def bm(self,str):
#以 UTF-8的文字编码打开json文件
f = open("weather_city.json", encoding='utf-8')
#对文件内容进行序列化
js=json.load(f)
#获取所有的省
for i in js['城市代码']:
x=i['市']
#获取所有的市
for n in x:
m=n['市名']
if m==str:
return n['编码']
return None
#获取客户的查询地址
def dz(self):
print("欢迎使用胖子集团天气查询系统!")
num=str(input('请输入您需要查询的地址(精确至地级市):\n'));
#查询地址所对应的编码
y=qx().bm(num)
#判断地址是否存在
if y==None:
print("输入城市名错误!")
else:
qx().tq(num,y)
if __name__ == '__main__':
qx().dz()