import requests

import json

def get_weather(city):

# 使用和风天气API(需替换成你的API Key)

api_key = "YOUR_API_KEY" # 替换为真实Key,免费注册获取

url = f"https://devapi.qweather.com/v7/weather/now?location=%7Bcity%7D&key=%7Bapi_key%7D%22

try:

response = requests.get(url)

data = json.loads(response.text)

if data["code"] == "200":

weather = data["now"]

print(f"""

====== {city} 天气 ======

温度:{weather['temp']}°C

体感温度:{weather['feelsLike']}°C

天气:{weather['text']}

湿度:{weather['humidity']}%

风向:{weather['windDir']}

=========================

""")

else:

print("城市名错误或API请求失败!")

except Exception as e:

print(f"错误:{e}")

if __name__ == "__main__":

city = input("请输入要查询的城市名(例如:北京): ")

get_weather(city)

Reply to this note

Please Login to reply.

Discussion

No replies yet.