玩轉百度即用API(5)——空氣質量指數查詢

空氣質量指數查詢,截至目前只能查到全國161個城市的數據。html

"三亞","三門峽","上海","東莞","東營","中山","臨安","臨汾","臨沂","丹東","麗水","義烏","烏魯木齊","九江","乳山","雲浮","佛山","保定","克拉瑪依","蘭州","包頭","北京","北海","南京","南充","南寧","南昌","南通","即墨","廈門","句容","台州","合肥","吉林","吳江","呼和浩特","咸陽","哈爾濱","唐山","嘉興","嘉峪關","大同","大慶","大連","天津","太倉","太原","威海","寧波","安陽","宜興","宜賓","宜昌","寶雞","宿遷","富陽","壽光","岳陽","常州","常德","常熟","平度","平頂山","廣州","庫爾勒","廊坊","延安","開封","張家口","張家港","張家界","徐州","德州","德陽","惠州","成都","揚州","承德","撫順","拉薩","招遠","揭陽","攀枝花","文登","無錫","日照","崑山","昆明","曲靖","本溪","杭州","棗莊","柳州","株洲","桂林","梅州","武漢","汕頭","汕尾","江門","江陰","瀋陽","滄州","河源","泉州","泰安","泰州","瀘州","洛陽","濟南","濟寧","海口","海門","淄博","淮安","深圳","清遠","溫州","渭南","湖州","湘潭","湛江","溧陽","濱州","濰坊","潮州","煙臺","焦做","牡丹江","玉溪","珠海","瓦房店","鹽城","盤錦","石嘴山","石家莊","福州","秦皇島","章丘","紹興","綿陽","聊城","肇慶","膠南","膠州","自貢","舟山","蕪湖","蘇州","茂名","荊州","榮成","萊州","萊蕪","萊西","菏澤","營口","葫蘆島","蓬萊","衡水","衢州","西寧","西安","諸暨","貴陽","赤峯","連雲港","遵義","邢臺","邯鄲","鄭州","鄂爾多斯","重慶","金華","金壇","金昌","銅川","銀川","錦州","鎮江","長春","長沙","長治","陽江","陽泉","青島","鞍山","韶關","馬鞍山","齊齊哈爾"
示例代碼:

#coding:utf-8
#version:0.1
#note:該即用API能查詢指定城市的空氣質量指數,但城市數量有限,截止2015年3月26日,只能查到全國161個城市的。



import urllib.request
import json
import collections
import urllib.parse

url = "http://apistore.baidu.com/microservice/aqi?city="

city = input("輸入你想查詢的城市:")
city = urllib.parse.quote(city)

url = url + city  #完整的URL
result = urllib.request.urlopen(url).read().decode("utf-8") 
info = json.loads(result,object_pairs_hook=collections.OrderedDict) #json格式轉換爲python格式,並指定爲有序字典

if (info['errNum'] == -1):      #查找失敗
    print(info['errMsg'])
else:                           #輸出天氣相關信息
    print("你查詢的城市空氣質量指數以下:")
    print("城市:", info['retData']['city'])
    print("採集時間:", info['retData']['time'])
    print("空氣質量指數:", info['retData']['aqi'])
    print("空氣等級:", info['retData']['level'])
    print("首要污染物:", info['retData']['core'])

輸出結果:

相關文章
相關標籤/搜索