用python做一个预测天气代码
时间: 2024-10-15 22:24:59 浏览: 18
在Python中,我们可以利用一些天气API来创建一个简单的天气预报代码。以下是一个基本示例,我们将使用requests库来获取天气数据,并展示如何从OpenWeatherMap API获取实时温度:
```python
import requests
import json
# 替换为你自己的API密钥和城市ID(可以去OpenWeatherMap官网注册并获取)
API_KEY = "your_api_key"
CITY_ID = "city_id" # 例如北京的城市ID是1010101,需要查找对应城市的ID
def get_weather_data(city_id):
base_url = "http://api.openweathermap.org/data/2.5/weather"
params = {
'appid': API_KEY,
'id': city_id,
'units': 'metric' # 使用摄氏度
}
response = requests.get(base_url, params=params)
if response.status_code == 200:
data = response.json()
main = data['main']
temp = main['temp'] # 获取当前温度
return temp
else:
print("Error fetching weather data.")
return None
def main():
temperature = get_weather_data(CITY_ID)
if temperature is not None:
print(f"当前气温:{temperature}°C")
else:
print("无法获取当前气温信息.")
if __name__ == "__main__":
main()
阅读全文