python接收免费天气API
时间: 2025-01-28 11:16:57 浏览: 62
### 使用Python调用免费天气API获取数据
为了实现这一目标,可以遵循几个主要环节来构建程序逻辑。首先,准备工作中涉及选择合适的免费天气API服务提供商并注册账号以获得API密钥[^1]。
#### 准备工作
确保安装了`requests`库用于发起HTTP请求。可以通过命令行工具pip轻松完成此操作:
```bash
pip install requests
```
#### 发送API请求
下面是一个简单的例子展示怎样使用Python向指定的天气API发出GET请求,并解析JSON格式的结果。这里假设使用的API支持通过城市名称查询天气情况:
```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)
if response.status_code == 200:
weather_data = response.json()
main_info = weather_data['main']
temperature = main_info['temp'] - 273.15 # Convert Kelvin to Celsius
description = weather_data['weather'][0]['description']
return {
'temperature': round(temperature, 2),
'condition': description.capitalize(),
}
else:
print(f"Error occurred while fetching data: {response.status_code}")
return None
if __name__ == "__main__":
city = input("Enter the name of a city: ")
key = "<Your_API_Key_Here>" # Replace with your actual API Key from OpenWeatherMap or another provider.
result = get_weather(city, key)
if result is not None:
print(f"The current temperature in {city.title()} is {result['temperature']}°C and it's currently {result['condition']}.")
```
这段代码展示了如何定义函数`get_weather()`接受两个参数——城市名和API密钥;随后构造完整的URL字符串并向其发送GET请求;最后根据服务器返回的状态码判断是否成功接收到有效响应,并据此执行不同的分支逻辑[^3]。
#### 处理返回的数据
当一切顺利时,会得到一个包含大量信息的对象作为回应。上述示例中只提取了温度(转换成摄氏度)以及天气状况描述这两项基本信息。实际应用可根据需求调整要读取的具体字段。
#### 错误处理
如果遇到问题,则打印出错提示连同状态码一起显示给用户查看。这有助于快速定位潜在的问题所在之处。
阅读全文
相关推荐


















