Python 天氣資料 API 取得器
使用標準庫在 Python 中取得即時天氣詳細資訊。了解 API 請求、JSON 轉換和模擬回退。
概述
整合第三方 API 是現代 Web 後端開發人員的關鍵技能。天氣獲取器將 Python 程式直接連接到即時氣候遙測伺服器。
通常,我們會使用外部“requests”模組,但Python的標準庫提供了“urllib.request”,它可以開箱即用,無需安裝依賴項。
此互動式腳本使用公共、開放存取的地理編碼端點來取得座標和溫度,說明了 try- except 解析循環、URL 編碼和 JSON 流讀取。
程式碼和執行輸出
查詢公共天氣遙測伺服器的標準庫 urllib 腳本。
weather_fetcher.py
在編輯器中嘗試import urllib.request
import json
def fetch_weather(city_lat, city_lon):
# Free, open weather API (No authentication key needed)
url = f"https://api.open-meteo.com/v1/forecast?latitude={city_lat}&longitude={city_lon}¤t_weather=true"
print(f"Connecting to Weather API for lat={city_lat}, lon={city_lon}...")
try:
req = urllib.request.Request(
url,
headers={'User-Agent': 'PyRun Weather Client/1.0'}
)
with urllib.request.urlopen(req, timeout=5) as response:
raw_data = response.read().decode('utf-8')
weather_json = json.loads(raw_data)
current = weather_json.get("current_weather", {})
temp = current.get("temperature")
wind = current.get("windspeed")
print("Successfully retrieved weather telemetry!")
print(f" Current Temperature: {temp}°C")
print(f" Wind Speed: {wind} km/h")
except Exception as e:
print(f"Could not retrieve weather details: {e}")
# Run fetch for Tokyo coordinates (lat: 35.6762, lon: 139.6503)
fetch_weather(35.6762, 139.6503)端子輸出
Connecting to Weather API for lat=35.6762, lon=139.6503...
Successfully retrieved weather telemetry!
Current Temperature: 22.4°C
Wind Speed: 14.2 km/h逐步實施
- 將天氣顯示小工具新增至自訂儀表板介面
- 編寫自動 cron 腳本來提醒使用者極端溫度事件
- 掌握urllib和標準函式庫網路協議
常見問題解答
該腳本可以在PyRun的瀏覽器引擎中運作嗎?
是的,PyRun的瀏覽器後端攔截 urllib 並請求套接字請求,將它們安全地轉換為瀏覽器級獲取查詢。
什麼是座標緯度和經度?
它們代表地球上的地理位置座標。緯度測量到赤道的南北距離,而經度測量距本初子午線的東西距離。