Python Weather API调用问题

时间:2016-12-15 16:20:42

标签: python api http openweathermap

我目前正在学习python并且在我的教学中达到了一个部分的结尾所以我想我会尝试用迄今为止学到的东西来构建一些基本项目。

我在git上找到了这个文件,并认为我会重新创建它并稍微修改它以允许用户输入,以便他们可以定制自己的城市/位置

然而,当我运行脚本时,我收到一个错误。请参阅下面的代码和错误。我不知道是应该将整个错误放在这里还是仅仅放在最后一行,所以我认为我在安全方面犯了错误并将其全部放入。如果它真的很长而且讨厌,那就道歉。

import urllib
import json

previous_weather_file = "weather_log.txt"
previous_weather = ""

try:
    log = open(previous_weather_file, "r")
    previous_weather = log.read()
    log.close()
except:
    print "No previous data"

city_name = raw_input("What is the city name you would like to check the weather for? ")

f = urllib.urlopen("api.openweathermap.org/data/2.5/weather?q={city_name}")
weather = f.read()

log = open(previous_weather_file, "w")
log.write(weather)
log.close()

weather_json = json.load(weather)
#print weather
#print weather_json['weather']
curr_temp = float(weather_json['main']['temp']) - 273.13
print "Temperature is %.2f degrees C" % (curr_temp)

if (not previous_weather == ""):
    previous_weather_json = json.load(previous_weather)
    prev_temp = float(previous_weather_json['main']['temp']) - 273.13
    temp_diff = curr_temp - prev_temp

    if not (temp_diff == 0.0):
        print "Temperature has changed by: %.2f degrees C" % (temp_diff)


#error message
Serxhios-MBP:Projects SerxhioZefi$ python weather_get.py
What is the city name you would like to check the weather for? London
Traceback (most recent call last):
  File "weather_get.py", line 16, in <module>
    f = urllib.urlopen("api.openweathermap.org/data/2.5/weather?q={city_name}")
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 87, in urlopen
    return opener.open(url)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 213, in open
    return getattr(self, name)(url)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 469, in open_file
    return self.open_local_file(url)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 483, in open_local_file
    raise IOError(e.errno, e.strerror, e.filename)
IOError: [Errno 2] No such file or directory: 'api.openweathermap.org/data/2.5/weather?q={city_name}'

1 个答案:

答案 0 :(得分:2)

将第16行更改为此(您缺少API的http或https)

f = urllib.urlopen("http://api.openweathermap.org/data/2.5/weather?q={city_name}")

接下来,您将遇到('http error', 401, 'Unauthorized', <httplib.HTTPMessage instance at 0x104827a70>),但这是另一个问题,与openweathermap API有关。我会检查他们的文档以了解API的用法。可能您需要在请求中包含身份验证密钥。

我建议在python中使用requests模块进行此类工作,主要是因为它使用起来很愉快并简化了许多任务:

http://docs.python-requests.org/en/master/