2016-12-15 37 views
0

我目前正在學習python,並在我的教導中到達了一節的結尾,所以我想我會嘗試使用迄今爲止學到的內容來構建一些基本項目。Python天氣API調用問題

我發現的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}' 

回答

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使用情況。可能您需要在請求中包含身份驗證密鑰。

我建議requests模塊對於這種類型的python的工作,主要是因爲它是愉快的使用,簡化了許多任務:

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