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

使用Python调用OpenWeatherMap API时出现KeyError: 'main'问题求助

Solution

Hey, let's break down why you're hitting that KeyError: 'main' and fix it step by step.

First, that error means the JSON response from OpenWeatherMap doesn't have a main key—and that's almost always because the API isn't returning valid weather data. Here are the most common causes, plus a robust fix for your code:

Common Reasons for the Error

  • Invalid or unactivated API key: Even if you filled it in, typos, extra spaces, or an unactivated key (some accounts require email verification first) will make the API return an error instead of weather data.
  • Malformed city name: Typos, extra spaces, or using non-English names without proper formatting can lead to the API not finding the city (and sometimes it won't return a 404 code—so your current cod != "404" check misses it).
  • Limited error handling: Your code only checks for a 404, but the API returns other error codes like 401 (unauthorized, bad key) or 400 (bad request) that don't include the main key.

Fixed Code with Better Error Handling

import requests  # Make sure you import this—your original code was missing it!

api_key = "your_valid_api_key_here"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = input("Enter city name : ").strip()  # Remove extra spaces from input
complete_url = f"{base_url}appid={api_key}&q={city_name}"  # Cleaner f-string formatting

try:
    # Send request and check for HTTP errors (like 401, 404, 500)
    response = requests.get(complete_url)
    response.raise_for_status()
    
    x = response.json()
    
    # Verify the response has the keys we need before accessing them
    if "main" in x and "weather" in x:
        y = x["main"]
        current_temperature = y["temp"]
        current_pressure = y["pressure"]
        current_humidiy = y["humidity"]
        z = x["weather"]
        weather_description = z[0]["description"]
        
        # Print results with cleaner formatting
        print(f"""Temperature (in kelvin unit) = {current_temperature}
Atmospheric pressure (in hPa unit) = {current_pressure}
Humidity (in percentage) = {current_humidiy}
Description = {weather_description}""")
    else:
        # Print the API's error message to debug easily
        print(f"API Error: {x.get('message', 'Unknown error occurred')}")

# Catch network/HTTP issues
except requests.exceptions.RequestException as e:
    print(f"Request failed: {str(e)}")
# Catch any remaining key errors just in case
except KeyError as e:
    print(f"Missing expected data in response: Key '{str(e)}' not found")

Key Improvements in This Code

  1. Added requests import: Your original code didn't include this—you'd get a NameError otherwise, so this is critical.
  2. Input cleaning: strip() removes extra spaces from the city name to avoid invalid requests.
  3. HTTP error checking: response.raise_for_status() catches issues like bad API keys (401) or server errors (500) before we even try to parse the JSON.
  4. Key existence checks: We verify main and weather exist in the response before accessing them, which prevents the KeyError.
  5. Clear error messages: If something goes wrong, you'll get a specific message to help you debug (like "Invalid API key" or "city not found").

内容的提问来源于stack exchange,提问作者Yarry T

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:06:45