我可以在英国开放式天气图中按邮政编码搜索吗

2024-03-28 17:02:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我从网上找到的教程中制作了一个非常简单的天气应用程序。我正在使用请求模块,我正在尝试调用英国邮政编码GU27PG的天气。我正在使用在https://openweathermap.org/current#zip找到的文档来构造我的url。这是我的密码:

import requests
import configparser


def get_api_key():
    config = configparser.ConfigParser()
    config.read('config.ini')
    return config['openweathermap']['api']



def get_weather_results(zip_code, country_code, api_key):
    api_url = 'http://api.openweathermap.org/data/2.5/weather?zip={},{}&appid={}'.format(zip_code, country_code, api_key)
    r = requests.get(api_url)
    return r.json()

print(get_weather_results("GU27PG", "UK", get_api_key()))

当我运行此命令时,它将返回以下命令:

{'cod': '404', 'message': 'city not found'} 

我敢肯定这是一个有效的邮政编码和国家代码。我曾经得到错误401,这意味着我的api密钥没有被激活,但它停止了,所以我的api密钥肯定能工作。 任何帮助都将非常感激


Tags: keyorgimportapiconfigurlgetcode
1条回答
网友
1楼 · 发布于 2024-03-28 17:02:53

您链接到的文档非常模糊,因此遇到绊脚石并不奇怪。我正要回答说,似乎无法使用zip参数搜索英国邮政编码,但通过实验,我发现了两件事:

  • 它只支持英国输出码(即邮政编码的“前半部分”)
  • 您需要的国家代码是GB,而不是英国

因此,在您的示例中,如果您要求它打印GU2,GB的天气结果,那么您将获得以下数据:

Response for GU2,GB

相关问题 更多 >