我需要一个python天气预报的源代码
时间: 2023-06-18 11:03:30 浏览: 60
以下是一个使用Python获取天气预报的示例代码:
```python
import requests
API_KEY = "YOUR_API_KEY" # 在 https://openweathermap.org/ 上注册并获取API KEY
CITY_NAME = "New York" # 城市名
url = f"http://api.openweathermap.org/data/2.5/weather?q={CITY_NAME}&appid={API_KEY}&units=metric"
response = requests.get(url)
weather_data = response.json()
if weather_data["cod"] != "404":
weather_description = weather_data["weather"][0]["description"]
temperature = weather_data["main"]["temp"]
feels_like = weather_data["main"]["feels_like"]
humidity = weather_data["main"]["humidity"]
wind_speed = weather_data["wind"]["speed"]
print(f"天气描述: {weather_description}")
print(f"温度: {temperature}℃")
print(f"体感温度: {feels_like}℃")
print(f"湿度: {humidity}%")
print(f"风速: {wind_speed}m/s")
else:
print("城市不存在")
```
请确保替换 `YOUR_API_KEY` 为您在 https://openweathermap.org/ 上注册并获取的API KEY。另外,您可能需要根据需要更改 `CITY_NAME`。此代码使用 `requests` 库从 OpenWeatherMap API 获取天气数据。