1、可以查询不同城市的天气情况和显示时间,每60秒刷新次天气情况,如图:
2、可以自由选择城市,选择之后立刻获取该城市的天气情况

# _*_ coding: utf-8 _*_
import requests
import time
def weather_log(stu):   #获取实时天气情况写入到文本
    cu_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    fp=open(‘weather.log‘,‘a‘)
    fp.write(‘{}  {}‘.format(cu_time,stu))
    fp.close()
#把文本中城市与城市ID一一对应的关系存进dic字典中
f=open(‘cityid.txt‘,‘r‘)
dic={}
for line in f:
    v=line.strip().split(‘,‘)
    dic[v[1]]=v[0]
f.close()
def update_weather(city):  #通过小米天气API获取天气状况
    if city in dic:
        cityid=dic[city]
        temp=requests.get("http://weatherapi.market.xiaomi.com/wtr-v2/temp/realtime?cityId="+cityid)
        temp.encoding=‘utf-8‘
        tem=temp.json()[‘weatherinfo‘][‘temp‘]
        SD=temp.json()[‘weatherinfo‘][‘SD‘]
        w=temp.json()[‘weatherinfo‘][‘WD‘]+temp.json()[‘weatherinfo‘][‘WS‘]
        weather=temp.json()[‘weatherinfo‘][‘weather‘]
        update_time=temp.json()[‘weatherinfo‘][‘time‘]
        stu=‘{0}此刻温度:{1} {2} {3}  天气更新时间:{4}\n‘.format(city,tem,weather,w,update_time)
        weather_log(stu)
    else :
        print("请确定城市是否正确")
    return (tem,SD,w,weather)这些只是关键代码,完整代码和cityid文件可在下面的链接中下载。
cityid的文件格式如下图:
关键程序很简单,就是通过cityid这文件生成cityid与城市名对应的字典,再通过小米的天气API去获取该城市的天气信息,请求的地址返回的是json格式的数据,所以直接用requests库中的json的方法访问即可,无需使用标准库的json库。
原文:http://blog.51cto.com/eddy72/2094788