以下是一个使用 Python 获取免费天气预报信息(基于 OpenWeatherMap API)的简单示例代码:
首先,你需要在 OpenWeatherMap 网站注册并获取一个免费的 API 密钥。
import requests
def get_weather(city, api_key):
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
weather = data['weather'][0]['description']
temperature = data['main']['temp'] - 273.15 # 将开尔文转换为摄氏度
print(f"{city}的天气是:{weather},温度是:{temperature:.2f}摄氏度")
else:
print("获取天气信息失败")
city = "北京"
api_key = "你的 API 密钥"
get_weather(city, api_key)
基础概念:
requests
库用于发送 HTTP 请求。优势:
类型:
应用场景:
可能出现的问题及原因:
领取专属 10元无门槛券
手把手带您无忧上云