2017-06-06 22 views
0

我努力學習,並要求通過連接到天氣API練習。但由於某種原因,我無法讓它工作?很明顯,天氣API以某種方式想要param,我似乎無法弄清楚它是如何轉化爲請求的。如何使用請求連接到天氣API?

這裏是我的代碼:

r = requests.get('http://api.openweathermap.org/data/2.5/weather', q={'Anderson'}) 

這裏是鏈接到API頁面: https://openweathermap.org/current

我看天氣頁想在Q =城市而言帕拉姆,但這個錯誤我得到的是:

​​

也是在這裏,我指的是請求頁面:http://docs.python-requests.org/en/master/

感謝您的幫助!

+0

你給了'request.GET中()'方法意想不到的關鍵字參數'q'。它只接受文檔中提到的特定參數 – fechnert

+0

我知道,正如我在我的問題中所述。我的問題是什麼是正確的關鍵字參數。 – RostSunshine

+0

您需要openweather'appid' https://openweathermap.org/appid#get –

回答

1

請查閱requests用戶手冊,至少quickstart guide。 REST風格的API,你將要使用願同q="City Name"參數GET請求。此外,您必須擁有appid併爲每個請求添加它。

  1. 註冊您的應用程序,並選擇一個定價計劃https://openweathermap.org/price
  2. 同時通過q="City Name"APPID=xxx參數

下面是相應的要求:

api_url = 'http://api.openweathermap.org/data/2.5/weather' 
appid = ...  
r = requests.get(url=api_url, params=dict(q='Anderson', APPID=appid)) 
+0

這是正確的,但它沒有回報信息。它只是完成了0錯誤。我儘管這是我需要API來回饋信息或需要更多信息嗎? – RostSunshine

+0

@RostSunshine你是否檢查過你收到的迴應對象?建議您可能需要閱讀手冊。 – Jkdc

+0

服務器響應401:未經授權。這意味着你應該通過認證。請求可以做到這一點http://docs.python-requests.org/en/master/user/authentication/ –

0

試着改變你到下面的一個呼叫(加入API密鑰的params):

r = requests.get('http://api.openweathermap.org/data/2.5/weather', params={'q': 'Anderson', 'APPID': YOUR_API_KEY}) 
0

你需要一個appid爲openweather,這個人使用免費(https://openweathermap.org/appid#get

>>> import requests 
>>> r = requests.get('http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1') 
>>> loc_weather = r.content.strip() 
>>> loc_weather 
'{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200}' 
+0

content.strip()是做什麼的? – RostSunshine

+0

如果有任何來自'r.content'的空白字符, –