一起学习网 一起学习网


构建简单天气查询应用

开发 Python weather app, OpenWeatherMap API, Python HTTP requests, weather data JSON, build weather application 06-07

构建一个简单的天气查询应用程序

在这个教程中,我们将使用Python和一个免费的天气API来构建一个简单的天气查询应用程序。这个应用将允许用户输入一个城市名,并返回该城市的当前天气情况。为了实现这个功能,我们将使用requests库来处理HTTP请求,并使用json库来解析API响应。

步骤1:准备工作

首先,我们需要确保已安装Python以及所需的库。打开终端或命令提示符,然后输入以下命令来安装requests库:

pip install requests

步骤2:注册获取API密钥

为了获取天气数据,我们将使用OpenWeatherMap的API。首先,你需要在OpenWeatherMap官网注册一个账户,并获取一个免费的API密钥。

步骤3:编写Python脚本

创建一个新的Python文件,名为weather_app.py。在这个文件中,我们将编写代码来查询天气数据。

import requests
import json

def get_weather(city_name, api_key):
    # OpenWeatherMap API的URL
    base_url = "http://api.openweathermap.org/data/2.5/weather?"

    # 完整的url地址
    complete_url = f"{base_url}q={city_name}&appid={api_key}"

    # 向服务器发送请求
    response = requests.get(complete_url)

    # 将响应数据转换为JSON格式
    weather_data = response.json()

    if weather_data["cod"] != "404":
        main = weather_data['main']
        wind = weather_data['wind']
        weather_desc = weather_data['weather'][0]['description']

        # 打印天气信息
        print(f"Temperature: {main['temp']}K")
        print(f"Humidity: {main['humidity']}%")
        print(f"Wind Speed: {wind['speed']} m/s")
        print(f"Weather Description: {weather_desc}")

    else:
        print("City not found.")

if __name__ == "__main__":
    city_name = input("Enter city name: ")
    api_key = 'YOUR_API_KEY_HERE'  # 用你自己的API密钥替换
    get_weather(city_name, api_key)

步骤4:运行应用程序

在终端中,导航到weather_app.py所在的目录,然后执行以下命令来运行程序:

python weather_app.py

输入一个城市名称,你应该会看到该城市的当前天气信息。

代码说明

  • requests.get():发送HTTP GET请求以获取天气数据。
  • json():将响应转换为JSON格式,以便于访问数据。
  • API URL和参数:使用城市名和API密钥构建请求URL。
  • 条件检查:检查响应代码是否为“404”,以确定城市是否存在。

通过这个简单的应用程序,你可以了解到如何使用Python与外部API进行交互,以及如何处理和解析JSON数据。这是构建复杂应用程序的基础技能,希望对你有所帮助!


编辑:一起学习网