对于刚踏入编程世界的 Python 小白来说,编写一个实用的程序可能是既期待又迷茫的事情。今天,我们将带领大家用短短 20 行代码实现一个天气查询机器人。通过这个简单的项目,不仅能让你快速上手 Python 编程,还能了解如何利用网络 API 获取数据,感受编程的趣味性和实用性。
一、准备工作:了解所需工具和接口
在开始编写代码之前,我们需要明确两件事:使用的开发工具和获取天气数据的接口。
- 开发工具:Python 代码可以在多种环境中编写和运行,对于初学者,推荐使用Visual Studio Code 或者 PyCharm社区版。这些编辑器具有代码高亮、智能提示等功能,能极大提升编写效率。当然,你也可以使用系统自带的文本编辑器,如 Windows 的记事本或 Mac 的文本编辑,但需要手动配置 Python 运行环境。
- 天气数据接口:我们将使用和风天气的免费 API(也可以选择其他天气 API,如心知天气等)。在使用前,需要先在和风天气官网注册账号,获取属于自己的 API 密钥(Key),该密钥是访问 API 的凭证。注册并登录后,在控制台中创建应用,即可获得 API 密钥。
二、核心代码解析
下面是实现天气查询机器人的 Python 代码,总共 20 行左右:
import requests
# 和风天气API的基本URL
url = "https://api.heweather.net/v7/weather/now"
# 填写你在和风天气获取的API密钥
params = {
"key": "your_api_key",
"location": "北京" # 可替换为你想查询的城市
}
# 发送GET请求获取天气数据
response = requests.get(url, params=params)
# 检查请求是否成功
if response.status_code == 200:
data = response.json()
# 提取关键天气信息
city = data["now"]["obsTime"].split(" ")[0]
temperature = data["now"]["temp"]
weather = data["now"]["text"]
print(f"{city} 当前温度:{temperature}°C,天气状况:{weather}")
else:
print("获取天气数据失败,请检查网络或API密钥")
接下来,我们逐行分析这段代码:
- 导入模块:
import requests
requests
是 Python 中用于发送 HTTP 请求的第三方库,使用它可以方便地从网络上获取数据。如果你的环境中没有安装该库,可以使用命令pip install requests
进行安装。
2. 设置 API 请求参数:
url = "https://api.heweather.net/v7/weather/now"
params = {
"key": "your_api_key",
"location": "北京"
}
url
定义了和风天气 API 获取实时天气数据的地址。params
是一个字典,包含了请求 API 所需的参数。其中,key
需要替换为你在和风天气官网获取的 API 密钥;location
指定了要查询天气的城市名称,可以根据需求修改为其他城市,如 “上海”“广州” 等。
3.发送请求并处理响应:
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
city = data["now"]["obsTime"].split(" ")[0]
temperature = data["now"]["temp"]
weather = data["now"]["text"]
print(f"{city} 当前温度:{temperature}°C,天气状况:{weather}")
else:
print("获取天气数据失败,请检查网络或API密钥")
requests.get(url, params=params)
发送一个 GET 请求到指定的 API 地址,并传递参数。请求的结果存储在response
变量中。response.status_code
用于获取请求的状态码。如果状态码为200
,表示请求成功,此时使用response.json()
将返回的 JSON 格式数据转换为 Python 的字典类型,方便提取数据。- 从返回的数据中,我们提取了观测日期(
city
)、当前温度(temperature
)和天气状况(weather
),并使用print
函数输出结果。如果状态码不为200
,则说明请求失败,打印错误提示信息。
三、运行程序与拓展
运行程序
将上述代码保存为一个.py
文件(例如weather_query.py
),然后打开命令行终端,切换到文件所在的目录,输入python weather_query.py
(如果你的 Python 安装配置正确),按下回车键,即可看到查询的城市天气信息。
程序拓展
- 用户输入城市:可以通过
input
函数获取用户输入的城市名称,使程序更加灵活。修改后的代码如下:import requests url = "https://api.heweather.net/v7/weather/now" params = { "key": "your_api_key" } city = input("请输入你想查询天气的城市:") params["location"] = city response = requests.get(url, params=params) if response.status_code == 200: data = response.json() temperature = data["now"]["temp"] weather = data["now"]["text"] print(f"{city} 当前温度:{temperature}°C,天气状况:{weather}") else: print("获取天气数据失败,请检查网络或API密钥")
- 获取更多天气信息:和风天气 API 还提供了更多详细的天气数据,如湿度、风速、气压等。你可以通过修改代码,从返回的数据中提取这些信息并展示。例如,获取湿度信息:
import requests url = "https://api.heweather.net/v7/weather/now" params = { "key": "your_api_key" } city = input("请输入你想查询天气的城市:") params["location"] = city response = requests.get(url, params=params) if response.status_code == 200: data = response.json() temperature = data["now"]["temp"] weather = data["now"]["text"] humidity = data["now"]["humidity"] # 提取湿度信息 print(f"{city} 当前温度:{temperature}°C,天气状况:{weather},湿度:{humidity}%") else: print("获取天气数据失败,请检查网络或API密钥")
完整代码
# 基础版本:固定城市查询 import requests url = "https://api.heweather.net/v7/weather/now" params = { "key": "your_api_key", "location": "北京" } response = requests.get(url, params=params) if response.status_code == 200: data = response.json() city = data["now"]["obsTime"].split(" ")[0] temperature = data["now"]["temp"] weather = data["now"]["text"] print(f"{city} 当前温度:{temperature}°C,天气状况:{weather}") else: print("获取天气数据失败,请检查网络或API密钥") # 拓展版本1:用户输入城市查询 import requests url = "https://api.heweather.net/v7/weather/now" params = { "key": "your_api_key" } city = input("请输入你想查询天气的城市:") params["location"] = city response = requests.get(url, params=params) if response.status_code == 200: data = response.json() temperature = data["now"]["temp"] weather = data["now"]["text"] print(f"{city} 当前温度:{temperature}°C,天气状况:{weather}") else: print("获取天气数据失败,请检查网络或API密钥") # 拓展版本2:获取湿度等更多信息 import requests url = "https://api.heweather.net/v7/weather/now" params = { "key": "your_api_key" } city = input("请输入你想查询天气的城市:") params["location"] = city response = requests.get(url, params=params) if response.status_code == 200: data = response.json() temperature = data["now"]["temp"] weather = data["now"]["text"] humidity = data["now"]["humidity"] print(f"{city} 当前温度:{temperature}°C,天气状况:{weather},湿度:{humidity}%") else: print("获取天气数据失败,请检查网络或API密钥")
通过这个简单的天气查询机器人项目,Python 小白们不仅完成了自己的第一个实用程序,还掌握了 HTTP 请求、数据提取等编程技能。希望大家以此为起点,继续探索 Python 编程的广阔世界,开发出更多有趣、有用的程序!