実現したいこと
OpenWeatherMap APIから任意の気象予報データを取得したいです.
前提
最近pythonを勉強し始めた人間です.
初めて質問させていただくため,情報不足など至らない点があるかもしれませんが,ご了承ください.
基礎を勉強し,現在は最高気温や最低気温,降水確率を取得し,任意の時間にLINEに表示するbotを作成中です.
apiから気象予報データを取得するコードがある程度書けたため,試しに東京の3時間後の予報の取得を試みました.
するとエラーが発生し,色々調べましたが理由が分からず,困惑しています.
どなたか分かる方がいらっしゃったら助けてください.
OpenWeatherMap APIで取得できるjson形式のapi応答フィールドは以下の通りとなります.
cod:内部パラメータ
message:内部パラメータ
cntAPI :応答で返されるタイムスタンプの数
list
ーlist.dt :予測されたデータの時刻 (UNIX、UTC)
ーlist.main
ーーーlist.main.temp:温度
ーーーlist.main.feels_likeこの温度パラメータは、人間の天候の認識を説明しています。
ーーーlist.main.temp_min:計算時の最低気温
ーーーlist.main.temp_max:計算時の最高温度。
ーーーlist.main.pressure:デフォルトの海面大気圧
ーーーlist.main.sea_level:海面上の大気圧
ーーーlist.main.grnd_level:地上の大気圧
ーーーlist.main.humidity:湿度
ーーーlist.main.temp_kf:内部パラメータ
ーlist.weather
ーーーlist.weather.id:気象条件 ID
ーーーlist.weather.main:気象パラメータのグループ(雨、雪、雲など)
ーーーlist.weather.description:グループ内の気象条件(晴れ,快晴など)
ーーーlist.weather.icon:天気アイコン ID
ーlist.clouds
ーーーlist.clouds.all:曇り度
ーlist.wind
ーーーlist.wind.speed:風速
ーーーlist.wind.deg:風向
ーーーlist.wind.gust:突風
ーーーlist.visibility:平均視程
ーーーlist.pop:降水確率
ーlist.rain
ーーーlist.rain.3h:過去3時間の雨量
ーlist.snow
ーーーlist.snow.3h:過去3時間の積雪量
ーlist.sys
ーーーlist.sys.pod:一日の一部(n - 夜、d - 日)
ーlist.dt_txt:予測されるデータの時刻、ISO、UTC
city
ーcity.id :市区町村 ID
ーcity.name 市区町村名
ーcity.coord
ーーcity.coord.lat :緯度
ーーcity.coord.lon:経度
ーcity.country :国コード(GB、JPなど)
ーcity.population市の人口
ーcity.timezone:UTC からの秒単位のシフト
ーcity.sunrise:日の出時刻 (ユニックス、UTC)
ーcity.sunset:サンセット時間, ユニックス, UTC
発生している問題・エラーメッセージ
KeyError: 'weather'
該当のソースコード
python
1#天気予報を取得する関数2def get_weather(latitude,longitude):3 #OpenWeatherMap APIキー4 api_key = '{my_api_key}'5 #url作成6 endpoint = 'https://api.openweathermap.org/data/2.5/forecast?lat={lat}&lon={lon}&units=metric&lang=ja&appid={api_id}&cnt={limit}'7 #取得する予報時刻の数8 request_line = 19 url = endpoint.format(lat = latitude , lon = longitude , api_id = api_key , limit = request_line)10 #APIから情報を取得(レスポンス)11 response = requests.get(url)12 #レスポンスの内容をJSONフォーマットからPythonフォーマットに変換13 response = response.json()14 #気象情報の取得15 climate = response['weather'][0]['description']16 temp_max = response['main']['temp_max']17 temp_min = response['main']['temp_min']18 precipitation = response['pop']19 #出力20 print(f'{weather}の予報です.')21 print(f'最高気温は{temp_max}℃です.')22 print(f'最低気温は{temp_min}℃です.')23 print(f'降水確率は{precipitation}%です.')24 if precipitation <= 0.5 :25 print('傘を持ち歩いた方が良いでしょう.お出かけの際は忘れずに!')26 else :27 print('傘は必要ありません.')28get_weather(35.6813,139.766)
試したこと
15行目の
climate = response['weather'][0]['description']
で発生していますが,この行全体をコメントアウトすると15行目で
Keyerror: 'main'
と出てきます.
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。

0 コメント