import requests
import json
def get_weather(city):
api_key = "003970a6825771f12dd5fe353479ff92" # 替换为你自己的API Key
base_url = "http://api.openweathermap.org/data/2.5/weather"
# 构建请求参数
params = {
"q": city, # 城市名
"appid": api_key, # API Key
"units": "metric" # 温度单位为摄氏度
}
# 发送GET请求获取天气数据
response = requests.get(base_url, params=params)
data = json.loads(response.text)
# 解析返回的JSON数据
if data["cod"] == 200:
weather = data["weather"][0]["main"] # 天气情况
description = data["weather"][0]["description"] # 天气描述
temperature = data["main"]["temp"] # 温度
humidity = data["main"]["humidity"] # 湿度
wind_speed = data["wind"]["speed"] # 风速
# 输出天气信息
print(f"Weather in {city}:")
print(f" - Weather: {weather} ({description})")
print(f" - Temperature: {temperature}°C")
print(f" - Humidity: {humidity}%")
print(f" - Wind Speed: {wind_speed} m/s")
else:
print("Failed to fetch weather data.")
# 测试
city_name = input("请输入城市名:")
get_weather(city_name)
https://home.openweathermap.org/申请账号后,将自己的API_KEY输入即可