You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于tkinter的IP定位天气查询功能报KeyError: 'name'求助

解决KeyError: 'name'的排查方案

可能的原因及排查步骤

1. ipBase API返回的数据结构与预期不符

你直接通过response.json()["data"]["location"]["city"]["name"]提取城市名,但实际API返回的JSON可能存在以下问题:

  • city字段为null(比如IP地址无法定位到具体城市)
  • 字段名不是name,而是其他命名(如city_name)
  • 层级结构和你假设的不同(比如location下直接包含city字段,而非嵌套更深层)

排查方法:在获取城市名前,先打印完整的API返回数据,确认实际结构:

print("IP API 返回内容:", response.json())

2. OpenWeather API返回错误响应

如果ipBase返回的城市名无效(比如格式错误、OpenWeather无法识别),OpenWeather会返回错误信息(如{"cod":"404", "message":"city not found"}),此时weather_data中没有name或main字段,触发KeyError。

排查方法:打印天气API的返回内容,并检查请求状态码:

print("天气API 返回内容:", weather_response.json())
print("请求状态码:", weather_response.status_code)

状态码非200时,说明请求失败,需要处理错误信息。

优化后的代码(含错误处理)

def get_location_weather():
    # 获取IP位置数据
    query_params = {"apiKey": api_Lkey}
    response = requests.get(ipURL, params=query_params)
    
    # 调试用:打印IP API返回的完整数据
    print("IP API Response:", response.json())
    
    # 安全提取城市名,避免KeyError
    city_name = response.json().get("data", {}).get("location", {}).get("city", {}).get("name")
    if not city_name:
        weather_label.config(text="无法获取当前城市位置")
        return
    
    # 获取天气数据
    weather_query_params = {
        'q': city_name,
        'appid': api_Wkey,
        'units': 'metric'
    }
    weather_response = requests.get(weather_URL, params=weather_query_params)
    
    # 调试用:打印天气API返回的完整数据
    print("Weather API Response:", weather_response.json())
    
    # 检查天气请求是否成功
    if weather_response.status_code != 200:
        error_msg = weather_response.json().get('message', '未知错误')
        weather_label.config(text=f"天气查询失败:{error_msg}")
        return
    
    weather_data = weather_response.json()
    
    # 安全提取天气信息
    city = weather_data.get('name')
    temp = weather_data.get('main', {}).get('temp')
    if city and temp is not None:
        weather_label.config(text=f"{city}: {temp}°C")
    else:
        weather_label.config(text="解析天气数据失败")

关键注意事项

  • 避免直接链式访问嵌套JSON的键,改用dict.get()方法,可指定默认值(如None),防止KeyError
  • 每次API请求后检查status_code,确保请求成功后再处理返回数据
  • 打印原始API返回内容是排查结构问题最有效的方式

内容的提问来源于stack exchange,提问作者Matthew Cowper-hill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 04:15:23