說明:個人開發使用時想到獲取天氣看看情況,然後找到了高德的API,獲取各個地區的天氣情況
高德地圖開發平台:https://lbs.amap.com/
點擊天氣服務API可以跳轉到天氣查詢的API文檔
第一步,申請”web服務 API”密鑰(Key);
第二步,拼接HTTP請求URL,第一步申請的Key需作為必填參數一同發送;
第三步,接收HTTP請求返回的數據(JSON或XML格式),解析數據。
URL:https://restapi.amap.com/v3/weather/weatherInfo?parameters
請求方式:GET
請求參數:key:你的應用key
city:查詢城市的城市編碼,下載城市編碼文檔
extensions:天氣類型:base/all。base:返回實況天氣;all:返回預報天氣。根據具體情況選擇。
import requests
url = 'https://restapi.amap.com/v3/weather/weatherInfo?parameters'
params_realtime = {
'key':'你的應用key',
'city':'360731', # 從城市編碼裡獲取的a丟包code
'extensions':'base' # 獲取實時天氣
}
params_estimate = {
'key':'你的應用key',
'city':'360731',
'extensions':'all' #獲取預報天氣
}
res = requests.get(url=url,params=params_estimate) # 預報天氣
res2 = requests.get(url=url,params=params_realtime) # 實時天氣
tianqi = res.json()
print(tianqi)
tianqi2 = res2.json()
print(tianqi2)
# print(tianqi.get('forecasts'))
# province = tianqi.get('forecasts')[0].get("province") # 獲取省份
province = tianqi['forecasts'][0]["province"] # 獲取省份
city = tianqi.get('forecasts')[0].get("city") # 獲取城市
adcode = tianqi.get('forecasts')[0].get("adcode") # 獲取城市編碼
reporttime = tianqi.get('forecasts')[0].get("reporttime") # 獲取發布數據時間
date = tianqi.get('forecasts')[0].get("casts")[0].get('date') # 獲取日期
week = tianqi.get('forecasts')[0].get("casts")[0].get('week') # 獲取星期幾
dayweather = tianqi.get('forecasts')[0].get("casts")[0].get('dayweather') # 白天天氣現象
nightweather = tianqi.get('forecasts')[0].get("casts")[0].get('nightweather') # 晚上天氣現象
daytemp = tianqi.get('forecasts')[0].get("casts")[0].get('daytemp') # 白天溫度
nighttemp = tianqi.get('forecasts')[0].get("casts")[0].get('nighttemp') # 晚上溫度
daywind = tianqi.get('forecasts')[0].get("casts")[0].get('daywind') # 白天風向
nightwind = tianqi.get('forecasts')[0].get("casts")[0].get('nightwind') # 晚上風向
daypower = tianqi.get('forecasts')[0].get("casts")[0].get('daypower') # 白天風力
nightpower = tianqi.get('forecasts')[0].get("casts")[0].get('nightpower') # 晚上風力
print("省份:",province)
print("城市:",city)
print("城市編碼:",adcode)
print("發布數據