python调用天气api
时间: 2025-02-25 22:52:30 浏览: 32
### 使用 Python 调用天气 API 的方法
为了使用 Python 获取实时天气数据,通常会采用 `requests` 库发送 HTTP 请求给提供天气信息服务的服务器。下面是一个简单的例子展示怎样利用该库来访问 OpenWeatherMap 提供的服务并解析返回的数据。
#### 安装依赖包
首先确保安装了 requests 库,可以通过 pip 工具完成安装:
```bash
pip install requests
```
#### 编写调用代码
接下来编写一段用于查询某城市当前天气状况的小程序:
```python
import requests
def get_weather(city_name, api_key):
base_url = "http://api.openweathermap.org/data/2.5/weather?"
complete_url = f"{base_url}q={city_name}&appid={api_key}"
response = requests.get(complete_url)
data = response.json()
if data["cod"] != "404":
main_data = data['main']
temperature = main_data['temp'] - 273.15 # Convert Kelvin to Celsius
pressure = main_data['pressure']
humidity = main_data['humidity']
weather_desc = data['weather'][0]['description']
result = (f"Temperature: {temperature:.2f}°C\n"
f"Pressure: {pressure} hPa\n"
f"Humidity: {humidity}%\n"
f"Weather Description: {weather_desc}")
return result
else:
return "City Not Found"
if __name__ == "__main__":
city = input("Enter city name : ")
key = 'your_api_key_here' # Replace with your actual API key from openweathermap.org
print(get_weather(city, key))
```
这段脚本定义了一个名为 `get_weather()` 函数接收两个参数——城市名称和 API 密钥。它构建完整的请求 URL 并向 Weather API 发送 GET 请求;如果响应状态码不是错误码,则进一步处理 JSON 数据提取所需的信息,并最终打印出来;反之则提示找不到对应的城市记录[^1]。
阅读全文
相关推荐















