簡體   English   中英

Python Weather API調用問題

[英]Python Weather API Call Issue

我目前正在學習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}'

將第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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM