# APIを使用したウェブクローラーを使用して天気情報を取得する ## Pythonの更新 [Python](https://www.python.org/)公式サイトにアクセスしてください! Downloadsの中のDownload for WindowsのPython 3.12.1をクリックしてください。 ![image](https://hackmd.io/_uploads/S1846orUa.png) ファイルを保存したら開いてください! Add python.exe to PATHにチェックを入れ、Install Nowをクリックしてください。 ![image](https://hackmd.io/_uploads/r18BTjrU6.png) ## VS codeの使用 Visual Studio Codeを開いてください。 左端の列で、「四つの小さいボックスの拡張機能を探してみて、見つけたらpythonを検索し、インストールしてください。」。 ![image](https://hackmd.io/_uploads/SkPwTsHL6.png) Pythonファイルを保存したフォルダを選んでください(名前は自分で決めればいいです)例: デスクトップ VS codeに戻り、ファイル ~に「フォルダを追加」をクリックしてください ![image](https://hackmd.io/_uploads/SJSdToHUT.png) 先ほど作成したフォルダを選択してください。 ![image](https://hackmd.io/_uploads/HkLFpjHIT.png) フォルダ内にPythonファイルを作成してください(名前は自分で決めればいいですが、その名前のあとに「.py」をつけてください。)。 ![image](https://hackmd.io/_uploads/SJgiTiSIT.png) モジュールをインポートしましょう。 ```python= import requests import json ``` ![image](https://hackmd.io/_uploads/ry1aaoSLa.png) ## APIを申請する https://openweathermap.org/ でアカウントを作成してください ![螢幕擷取畫面 2023-12-12 203342](https://hackmd.io/_uploads/Hkb_XRr8T.png) プロフィールから自分のAPIキーが取得できます ![image](https://hackmd.io/_uploads/BJ6gNABI6.png) コマンド部分から天気情報を取得するために、丸の付けてあるところのURLを覚えてください。(コピーしてもいいです) (山口県立宇部高校の座標は、33.962536523925955, 131.26874472524221です。) ![image](https://hackmd.io/_uploads/HyRJr0B86.png) ## データを取得する VS codeに戻り、入力してください ```python= data = requests.get( 'https://api.openweathermap.org/data/2.5/weather?lat={探している場所の緯度}&lon={探している場所の経度}&appid={あなたのAPIキー}') data_json = data.json() # 轉換成 JSON 格式 with open('weather.json', 'w', encoding='utf-8')as file: json.dump(data_json, file, ensure_ascii=False) ``` ![image](https://hackmd.io/_uploads/SkIlICS8p.png) Pythonファイルを実行する ![image](https://hackmd.io/_uploads/HJLm8RBLa.png) 左側に weather.json という「追加されたファイル」があるはずです ![image](https://hackmd.io/_uploads/HJaYLCHIa.png) クリックして中に入ると、かなり乱雑なテキストが表示されます ![image](https://hackmd.io/_uploads/ry3i8RB86.png) VS codeの設定に移動しましょう ![image](https://hackmd.io/_uploads/HykTI0HIp.png) "format on save"を入力し、チェックを入れてください ![image](https://hackmd.io/_uploads/HJsCLAHI6.png) weather.jsonに戻り、control + s を押してください(ファイルの解説を保存) ![image](https://hackmd.io/_uploads/BkQlwCBLa.png) ## 最後のコード  以下は完成したコードです ```python= import requests import json data = requests.get( 'https://api.openweathermap.org/data/2.5/weather?lat=33.96254987171882&lon=131.26869108089363&appid=7b476625b32aed3287aac75cd1aeae12') data_json = data.json() # 轉換成 JSON 格式 with open('weather.json', 'w', encoding='utf-8')as file: json.dump(data_json, file, ensure_ascii=False) weather = data_json["weather"][0]['main'] humidity = data_json['main']['humidity'] temp = data_json['main']["temp"]-273.15 location = data_json['name'] print(f"location: {location}") print(f"weather: {weather}") print(f"humidity: {humidity}") print(f"temperture: {round(temp)}") ``` ![image](https://hackmd.io/_uploads/r1aLDCr86.png)