LoginSignup
16
17

More than 5 years have passed since last update.

pythonを使ってOpenWeatherMapから天気情報を取得

Last updated at Posted at 2018-07-06

背景

Nature Remoで測定した室温と天気の気温を比較してみたい。
調べたらいろいろ方法出て来るけど、調べたのとは微妙に違うやりかたでjsonを表示してみた。

環境

  • GCPの無償のVMインスタンス
  • python 3.6.3

やったこと

OpenWeatherMap

OpenWeatherMapを登録。
Sign UpしてAPI Keysを確認。

Сurrent weather and forecast - OpenWeatherMap

Python

認証もなく、くせのないAPIなのでシンプル。

import requests
import json

city_name = "Kobe" # 主要な都市名はいけるっぽい。
API_KEY = "xxx" # xxxに自分のAPI Keyを入力。
api = "http://api.openweathermap.org/data/2.5/weather?units=metric&q={city}&APPID={key}"

url = api.format(city = city_name, key = API_KEY)
print(url)
response = requests.get(url)
data = response.json()
jsonText = json.dumps(data, indent=4)
print(jsonText)

結果

いろんな情報入ってる。units=metricで聞いてるから、摂氏で温度見れる。

{
    "coord": {
        "lon": 135.19,
        "lat": 34.69
    },
    "weather": [
        {
            "id": 803,
            "main": "Clouds",
            "description": "broken clouds",
            "icon": "04n"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 26,
        "pressure": 1006,
        "humidity": 83,
        "temp_min": 26,
        "temp_max": 26
    },
    "visibility": 10000,
    "wind": {
        "speed": 10.3,
        "deg": 190
    },
    "clouds": {
        "all": 75
    },
    "dt": 1530889200,
    "sys": {
        "type": 1,
        "id": 7514,
        "message": 0.1609,
        "country": "JP",
        "sunrise": 1530820333,
        "sunset": 1530872140
    },
    "id": 1855207,
    "name": "Kobe",
    "cod": 200
}

所感

簡単に情報とれて便利。
精度はどうなんやろ。
次、Nature Remoで取得した室温との違いを見れるようにしたい。

参考

無料天気予報APIのOpenWeatherMapを使ってみる - Qiita

PythonでOpenWeatherMapから東京の天気を定期的に取得して保存する - 渋谷ほととぎす通信

OpenWeatherMap API v2.5から天気を取得する - Qiita

Nature Remoで測定した室温をThingSpeakに渡して表示。 - Qiita

16
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
17