和風天氣網址:https://www.heweather.com/
注冊后在控制台會有個人認證key
API幫助文檔:https://www.heweather.com/documents/api/v5
#!/usr/bin/python
#-*-coding:utf-8-*-
#調用和風天氣API查詢當前天氣信息
#2017/07/12
import json
import urllib2
import os
city='北京'
#在和風天氣注冊后獲得的key
key='your key'
city_name={'北京':'beijing','上海':'shanghai'}
city_hname=city_name.get(city)
#獲取當前天氣信息
def get_json(city):
url='https://free-api.heweather.com/v5/now?city='+city_hname+'&key='+key
# print url
html=urllib2.urlopen(url).read()
return html
# print html
# f=open(city_hname+'.txt','w')
# f.write(html)
# f.close
#get_json(city)
#解析json數據
#data=open(city_hname+'.txt').readline()
data=get_json(city)
hjson=json.loads(data)
basic_status=hjson['HeWeather5'][0]['basic']
nowtq_status=hjson['HeWeather5'][0]['now']
#print now
#print now_status['cond']['txt'].encode('utf-8')
#格式化輸出城市信息
def basic(databasic):
print '國家/城市名稱:\t%s/%s'%(databasic['cnty'].encode('utf-8'),databasic['city'].encode('utf-8'))
print '信息更新時間:\t%s'%(databasic['update']['loc'].encode('utf-8'))
#basic(basic_status)
#格式化輸出當前天氣信息
def tqms(datanowtq):
print '當前室外溫度:\t%s度'%(datanowtq['tmp'].encode('utf-8'))
#print '體感溫度:\t%s'%(datanowtq['fl'].encode('utf-8'))
print '天氣描述:\t%s'%(datanowtq['cond']['txt'].encode('utf-8'))
print '相對濕度(%):\t'+'%s%%'%(datanowtq['hum'].encode('utf-8'))
print '風力/風向:\t%s/%s級'%(datanowtq['wind']['dir'].encode('utf-8'),datanowtq['wind']['sc'].encode('utf-8'))
print '能見度(km):\t%skm'%(datanowtq['vis'].encode('utf-8'))
basic(basic_status)
tqms(nowtq_status)
坑:
1.使用print格式化輸出百分號的時候要使用%%,例:
>>> print '%d%%' % 23 23%
