import requests # ===================== 配置区(仅需替换你的高德Key)===================== GAODE_KEY = "ff608780d5d18bab2f875a62b9c0c106" # 必须是Web服务类型Key # ====================================================================== # 高德API基础地址 GEO_URL = "https://restapi.amap.com/v3/geocode/geo" # 地理编码(城市名转ADCODE) WEATHER_URL = "https://restapi.amap.com/v3/weather/weatherInfo" # 天气API def get_city_adcode(city_name: str) -> str: """ 【核心函数】传入城市名称字符串,返回高德ADCODE编码 :param city_name: 城市名(如:北京、上海市、深圳、朝阳区、杭州) :return: 城市ADCODE编码,失败返回None """ params = { "key": GAODE_KEY, "address": city_name, # 传入的城市名称 "output": "json" } try: response = requests.get(GEO_URL, params=params, timeout=10) data = response.json() # 调用成功,解析ADCODE if data.get("status") == "1" and data.get("geocodes"): adcode = data["geocodes"][0]["adcode"] print(f"✅ 城市【{city_name}】匹配成功,ADCODE编码:{adcode}") return adcode else: print(f"❌ 未找到城市【{city_name}】,请检查城市名称是否正确") return None except Exception as e: print(f"❌ 查询编码失败:{str(e)}") return None def get_gaode_weather(adcode: str, is_forecast=False): """调用高德天气API(实时/4天预报)""" params = { "key": GAODE_KEY, "city": adcode, "extensions": "base" if not is_forecast else "all", "output": "json" } try: response = requests.get(WEATHER_URL, params=params, timeout=10) data = response.json() return data if data.get("status") == "1" else None except: return None def format_weather_info(data) -> str: """格式化天气信息并返回字符串""" if not data: return "天气数据获取失败" result = [] # 实时天气 if "lives" in data: live = data["lives"][0] result.append(f"【实时天气】") result.append(f"城市:{live['city']}") result.append(f"天气:{live['weather']}") result.append(f"温度:{live['temperature']}℃") result.append(f"风向:{live['winddirection']}风") result.append(f"风力:{live['windpower']}级") result.append(f"湿度:{live['humidity']}%") # 4天预报 if "forecasts" in data: forecast = data["forecasts"][0] result.append(f"\n【{forecast['city']} 4天预报】") for day in forecast["casts"]: result.append(f"{day['date']}:白天{day['dayweather']},夜间{day['nightweather']},气温{day['nighttemp']}~{day['daytemp']}℃") return "\n".join(result) def print_weather_info(data): """格式化打印天气信息""" print(format_weather_info(data)) def get_tianqi_data(city_name: str) -> str: """ 【供外部调用的主函数】传入城市名称,返回格式化的天气信息字符串 :param city_name: 城市名称(如:北京、上海、深圳) :return: 格式化的天气信息字符串 """ # 1. 获取城市ADCODE adcode = get_city_adcode(city_name) if not adcode: return f"未找到城市【{city_name}】的天气信息" # 2. 获取实时天气 realtime = get_gaode_weather(adcode, is_forecast=False) # 3. 获取4天预报 forecast = get_gaode_weather(adcode, is_forecast=True) # 4. 合并结果 result = [] if realtime: result.append(format_weather_info(realtime)) if forecast: result.append(format_weather_info(forecast)) return "\n\n".join(result) if result else f"获取【{city_name}】天气失败" # ===================== 使用示例(直接改这里的城市名)===================== # if __name__ == "__main__": # # 1. 传入城市名称(字符串),自动获取编码 # city_name = "北京" # 这里修改为你要查询的城市:上海、广州、深圳、成都、重庆等 # city_adcode = get_city_adcode(city_name) # # 2. 获取编码成功后,查询天气 # if city_adcode: # # 实时天气 # realtime = get_gaode_weather(city_adcode, is_forecast=False) # print_weather_info(realtime) # # 4天预报 # forecast = get_gaode_weather(city_adcode, is_forecast=True) # print_weather_info(forecast)