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

Python调用OpenWeatherMap API获取天气温度异常问题排查

问题诊断与修复

你的代码无法运行的核心原因是缺少OpenWeatherMap API的认证密钥——所有调用该API的请求都必须携带appid参数,否则会返回权限错误。

修复步骤:

  1. 先去OpenWeatherMap官网注册账号,获取你的API密钥(免费版即可)
  2. 在代码的params字典中添加appid字段,填入你的密钥
  3. 补充更完善的错误处理,方便排查各类问题

修改后的完整代码:

import requests

def get_temperature(city_name):
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    # 替换成你自己的API密钥
    api_key = "你的API密钥"
    params = {
        "q": city_name,
        "units": "metric",
        "appid": api_key
    }

    try:
        response = requests.get(base_url, params=params)
        response.raise_for_status()  # 主动抛出HTTP错误
        data = response.json()
        
        temperature = data["main"]["temp"]
        return temperature
    except requests.exceptions.HTTPError as e:
        # 根据API返回的错误信息给出具体提示
        error_data = response.json()
        print(f"请求错误: {error_data.get('message', '未知错误')}")
        return None
    except KeyError:
        print("API返回数据格式异常,无法提取温度信息")
        return None
    except Exception as e:
        print(f"网络或其他异常: {str(e)}")
        return None

def main():
    city_name = input("Enter the name of the city: ")

    temperature = get_temperature(city_name)
    if temperature is not None:
        print(f"The current temperature in {city_name} is {temperature}°C.")

if __name__ == "__main__":
    main()

额外注意事项:

  • 确保输入的城市名称拼写正确(支持英文城市名,如"Beijing"或"New York")
  • 免费版API有调用次数限制,避免过于频繁的请求
  • 如果遇到城市名歧义,可在params中添加country字段(例如"country": "CN")来缩小查询范围

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:46:00