2017-01-03 51 views
1

我沒有改變我的代碼,但現在當我嘗試運行它,我得到是工作過,但沒有得到urllib.error.HTTPError:HTTP錯誤400:錯誤的請求

urllib.error.HTTPError: HTTP Error 400: Bad Request 

在此線

response = urlopen(url).read().decode('utf8') 

URL是

url = 'http://api.wunderground.com/api/f8cb961c53baad52/geolookup/conditions/q/{}/{}.json'.format(state.strip(), city) 

我是否應該等到稍後再試一次,因爲它是工作,直到剛剛一個小時前。

編輯:

我使用Python 3.5和已更改爲

url = quote("http://api.wunderground.com/api/f8cb961c53baad52/geolookup/conditions/q/{}/{}.json").format(state.strip(), city) 

這將導致URL

http%3A//api.wunderground.com/api/f8cb961c53baad52/geolookup/conditions/q/%7B%7D/%7B%7D.json 

和錯誤消息

ValueError: unknown url type: 'http%3A//api.wunderground.com/api/f8cb961c53baad52/geolookup/conditions/q/%7B%7D/%7B%7D.json' 

編輯2:

我用

url = 'api.wunderground.com/api/f8cb961c53baad52/geolookup/conditions/q/{}/{}.json'.format(state.strip(), city) 
print (url) 
url1 = quote(url) 
url2 = 'http://'+ url1 

要編碼的空間,但我仍然得到400錯誤。我會等到明天再試一次,因爲或許我的訪問存在問題。

編輯: 它正在與沒有空間的城市合作。所以我會繼續努力讓自己的空間工作。謝謝你的幫助。

+0

我認爲你的'url'變量的格式不正確的可能性更大。這是[HTTP錯誤400的含義](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes):服務收到請求但無法理解。在調用urlopen()之前,請打印'url'來驗證狀態和城市是否按照您的預期進行插值。 –

+0

我已經這樣做了,我得到了這個http://api.wunderground.com/api/f8cb961c53baad52/geolookup/conditions/q/ID/Boise City.json當我去那個網址我自己打開沒有問題。但現在任何城市,我一直在嘗試我的文件不起作用。 – Sam

+0

你應該使用'urllib.quote()'來編碼你的變量,因爲URL中的空格會使urlopen搞亂。請參閱http://stackoverflow.com/questions/21735801/how-to-send-a-urllib2-request-with-added-white-spaces –

回答

0

只需在您的Web瀏覽器中粘貼示例URL查詢,並根據回覆,您可能會發現您已經使用過API或者由於使用條款而阻止了您。我測試了它,它適用於我。

編輯:PYTHON 3.5工作!

import requests 
import json 
url = "http://api.wunderground.com/api/f8cb961c53baad52/geolookup/conditions/q/{}/{}.json".format('AZ', 'Chandler') 
response = requests.get(url=url) 
response.json() 

輸出:

{ 'current_observation':{ 'UV': '0',
'dewpoint_c':5,
'dewpoint_f':41,
'dewpoint_string':' 41 F(5℃)」,
'DISPLAY_LOCATION':{ '城市': '錢德勒',
'國家': '美國',
'country_iso3166': '美國',
....

+0

我認爲這也可能是問題,但是當我去那個網站的管理功能時,我沒有看到我對他們的API進行了太多的調用。但我會等到明天再試。謝謝。 – Sam

+0

速率限制;超賣政策。 (a。)KEY;監測。對API可以免費進行請求的數量有每日限制和分鐘限制。只有當您成爲付費用戶或成爲付費用戶時,您纔可能超過此門檻。 WUL將監控您每日使用API​​的情況,以確定您是否已通過使用應用程序編程接口密鑰(「密鑰」)超過了免費使用閾值。有關產品定價,套餐功能和費率限制級別,請參閱「按鍵設置」頁面。 – Shobeir

+0

我以爲我沒有超過限制,因爲之前我收到一封電子郵件,說我已經過去了,這次我什麼都沒有收到。 – Sam