当前位置: 首页 > news >正文

制作大模型获取天气数据工具(和风API)

先访问和风天气获取API

初始化API客户端

一些教程使用以下网站构造url将报错

"https://geoapi.qweather.com/v2/"
"https://api.qweather.com/v7/"
"https://devapi.qweather.com/v7/"

正确url构造格式为(your_api_host改为自己的):

"https://your_api_host/geo/v2/city/lookup?location=beij"
"https://your_api_host/v7/weather/now?location=101010100"

以下为2025.9.23的最新初始化和风天气API客户端

import time
import requests
import datetimeclass QWEATHER:_api_host = "输入你自己的API host"def __init__(self, api_key):self.API_KEY = api_keydef search_city(self, location):"""根据城市名称查询城市ID"""url = f"https://{self._api_host}/geo/v2/city/lookup"params = {"location": location}response = self.http_request_v2(url, method="GET", headers=self.headers(), params=params)if response and response.get("code") == "200" and response.get("location"):return response["location"][0]["id"]  # 返回第一个匹配的城市IDreturn Nonedef get_current_weather(self, location_id):"""获取指定城市ID的当前天气"""url = f"https://{self._api_host}/v7/weather/now"params = {"location": location_id}response = self.http_request_v2(url, method="GET", headers=self.headers(), params=params)return response# 生成 headers 头def headers(self, params=None):headers = {'Content-Type': 'application/json','X-QW-Api-Key': f'{self.API_KEY}'}return headersdef http_request_v2(self, url, method="GET", headers={}, params=None, max_retries=2, timeout=3):headers = headers or {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36'}headers.update(self.headers())for attempts in range(1, max_retries + 1):try:if method == "GET":response = requests.get(url, headers=headers, params=params, timeout=timeout)elif method in ("POST", "DELETE"):response = requests.request(method, url, json=params, headers=headers, timeout=timeout)response.raise_for_status()return response.json()except Exception as e:print([datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), attempts, url, method, params, headers, repr(e)])time.sleep(timeout * attempts)return None

格式化输出天气

def format_current_weather(response, city_name):"""格式化输出天气数据"""if not response or response.get("code") != "200":return f"无法获取{city_name}的天气,请稍后重试"else:now = response.get("now")update_time = response.get("updateTime", "").split("T")[1].split("+")[0]  # 提取时间部分weather_info = f"{city_name}当前({update_time})的天气是{now.get('text', '未知')},"weather_info += f"气温{now.get('temp', '未知')}℃,"weather_info += f"{now.get('windDir', '未知')}{now.get('windScale', '未知')}级,"weather_info += f"湿度{now.get('humidity', '未知')}%"return weather_info

测试

if __name__ == '__main__':api_key = "输入你自己的APi keys"client = QWEATHER(api_key)city_name = input("请输入城市名称(例如:广州):").strip()city_id = client.search_city(city_name)if not city_id:print(f"未找到城市:{city_name},请检查")else:weather_response = client.get_current_weather(city_id)print(format_current_weather(weather_response, city_name))

测试结果如下

http://www.dtcms.com/a/398147.html

相关文章:

  • Nginx服务部署与配置(Day.2)
  • 计算机课程《网络安全》课程导览:开启数字世界的守护之旅
  • 网站系统开发精品网站开发
  • 国外ps网站产品推广方案ppt
  • 【MuJoCo学习笔记】#2 接触动力学 腱系统 执行器 传感器
  • 北京 旅游攻略
  • python+django/flask+springboot个性化旅游推荐系统(数据可视化) 景点推荐 路线匹配 用户画像建模 智能搜索筛选 图文展示系统
  • 智慧校园信息门户网站建设一站式做网站哪家好
  • 携程HR面(准备)
  • Qt 框架知识体系
  • 如何重新编译HyperLPR原生库以消除16k对齐警告
  • [QT]常用控件属性一
  • QT 编写应力分析软件
  • INTLAB区间工具箱在区间分析算法中的应用与实现
  • 北京网页设计新趋势黄石市seo关键词优化怎么做
  • 【Linux】拆解 Linux 容器化核心:Namespace 隔离 + cgroups 资源控制,附 LXC 容器生命周期实战
  • VSCode IDE环境的python 显示:Import “rclpy“ could not be resolvedPylancer
  • 吴镇宇做的电影教学网站石家庄最新消息今天
  • MySQL笔记8
  • 【C++无数组矩阵对角线平均值保留2位小数】2022-11-18
  • 阿里巴巴网站费用怎么做分录烟台企业展厅设计
  • ZooKeeper与Kafka分布式协调系统实战指南:从基础原理到集群部署
  • lesson66:JavaScript BOM与DOM全解析:从基础到现代前端实践引言:前端开发的两大基石
  • UNIAPP如何自定义全局方法?
  • 040 线程控制
  • 前端开发利器:nvm、npm与pnpm全面解析与TypeScript/JavaScript选择指南
  • 电影网站如何做seo哪家网站建设公司好
  • LeetCode 刷题【90. 子集 II】
  • Spring Boot启动报错:Failed to configure a DataSource 全面解析与解决方案
  • MongoDB源码delete分析观察者getOpObserver()->onDelete