2016-12-15 8 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の使用法をチェックします。おそらく、あなたの要求に認証キーを含める必要があります。

私はそれを使用して楽しいですし、多くのタスクを簡素化する主な理由は、Pythonでこの種の作業のためrequestsモジュールをお勧めします。

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