# 透過API網路爬蟲取得天氣 ## 更新 Python 前往[python](https://https://www.python.org/)官網! 點選 Downloads 底下的 Download for Windows 的Python 3.12.1  儲存完畢後開啟檔案! 把 Add python.exe to PATH 打勾,然後點 Install Now  ## 使用 VS code 打開 Visual Studio Code 在最左邊的那行找到四個小格子的 延伸模組 並查詢 python 並點 install  找一個地方創等一下放Python檔案的資料夾(名字隨便) ex:桌面 回到 VS code 點選 file -> Add folder to Workplace  選取你剛剛創的資料夾  在你的資料夾底下創一個python檔(名字隨便,記得加 .py 就好)  載入 module ```python! import urllib.request as requests import json ```  ## 取得中央氣象局API 去 中央氣象局的 [氣象資料開放平台] 點 登入/註冊(https://opendata.cwb.gov.tw/index)  點氣象會員登入(facebook的沒辦法用) 下面的 加入會員  自己輸入帳密  去gmail確認註冊  回來登入  按取得授權碼  點資料主題的全部  查 36小時天氣預報  點進去 -> 選API  點 try it out  在 Authorization 輸入剛剛的授權碼  把 location 定在高雄 (其他都不用管)  滑到下面點 Excute  複製他給你的 url  ## 取得資料 回到 VS code 打入以下程式碼(我現場解釋) ```python= with requests.urlopen('你剛剛複製的的url')as response: data_json = json.load(response)# 轉換成 JSON 格式 with open('weather.json', 'w', encoding='utf-8')as file: json.dump(data_json, file, ensure_ascii=False) ```  儲存後執行檔案  應該會看到你左邊有多出一個檔案叫 weather.json  點進去後會看到一段很亂的東西  去VS code的設定  輸入 format on save 並打勾  回weather.json 按 control + s (現場教學解讀檔案)  ## 最後的程式碼 以下是最後的程式碼 ```python= import urllib.request as requests import json with requests.urlopen('你剛剛複製的的url')as response: data_json = json.load(response)# 轉換成 JSON 格式 with open('weather.json', 'w', encoding='utf-8')as file: json.dump(data_json, file, ensure_ascii=False) location = data_json['records']['location'][0]['weatherElement'][0]['time'][1]['parameter']['parameterName'] PoP = data_json['records']['location'][0]['weatherElement'][1]['time'][1]['parameter']['parameterName'] MinT = data_json['records']['location'][0]['weatherElement'][2]['time'][1]['parameter']['parameterName'] Ci = data_json['records']['location'][0]['weatherElement'][3]['time'][1]['parameter']['parameterName'] MaxT = data_json['records']['location'][0]['weatherElement'][4]['time'][1]['parameter']['parameterName'] print(f"天氣: {location}") print(f"降雨率: {PoP}") print(f"氣溫: {MinT} ~ {MaxT}") print(f"舒適度: {Ci}") ``` 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up