用Python编写一个实时天气的程序
用Python编写一个实时天气的程序

用Python编写一个实时天气的程序

首先,需要注册一个和风天气的账号,并且获得一个API Key。https://console.qweather.com在注册成功并获得API Key之后,我们可以通过Python中的requests库向和风天气API发送请求。

使用input()函数来提示用户输入城市名称,并将用户输入的城市名称作为请求URL的参数。

可以先根据城市名称获取城市ID,然后将城市ID用于查询实时天气信息。

这里输出了城市名称和所查询城市的天气信息。

完整代码如下:

import requests
import time

api_key = "xxxxxxxxxxxxxxxxxxxx"
city_name = input("请输入城市名称:")

# 通过城市查询接口获取城市ID
city_url = f"https://geoapi.qweather.com/v2/city/lookup?key={api_key}&location={city_name}&lang=zh"

city_response = requests.get(city_url)
city_data = city_response.json()

if city_data["code"] == "200":
    city_id = city_data["location"][0]["id"]
    print(f"城市 {city_name} 对应的城市ID 为:{city_id}")
    
    # 使用城市ID查询实时天气信息
    weather_url = f"https://devapi.qweather.com/v7/weather/now?key={api_key}&location={city_id}"
    weather_response = requests.get(weather_url)
    weather_data = weather_response.json()

    if weather_data["code"] == "200":
        now = weather_data["now"]
        print(f"{city_name}的天气情况:")
        print(f"天气状况:{now['text']}")
        print(f"温度:{now['temp']}℃")
        print(f"体感温度:{now['feelsLike']}℃")
        print(f"风向:{now['windDir']}")
        print(f"风速:{now['windSpeed']}km/h")
    else:
        print("获取天气信息失败!")
else:
    print("获取城市信息失败!")
time.sleep(5)

下面是一个简单的 Python 实现,它使用 OpenWeatherMap API 获取当前城市的天气数据,并在控制台中显示温度、湿度和天气状况:

import requests

api_key = "xxxxxxxxxxxxxxxxxxxx" # 在OpenWeatherMap网站注册API key

city = input("请输入城市名称:")

url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"

response = requests.get(url)

if response.status_code == 200:
data = response.json()
print(f"城市: {data['name']}")
print(f"温度: {data['main']['temp']}°C")
print(f"湿度: {data['main']['humidity']}%")
print(f"天气状况: {data['weather'][0]['description']}")
else:
print("获取天气信息失败")

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Title - Artist
0:00