2015-01-13 75 views
11

我正在使用geopy來對某些地址進行地理編碼,並且想要捕獲超時錯誤並將其打印出來,以便我可以對輸入進行一些質量控制。我將地理編碼請求放入try/catch中,但它不起作用。關於我需要做什麼的任何想法?Geopy:捕獲超時錯誤

這裏是我的代碼:

try: 
    location = geolocator.geocode(my_address)    
except ValueError as error_message: 
    print("Error: geocode failed on input %s with message %s"%(a, error_message)) 

我得到以下異常:

File "/usr/local/lib/python2.7/site-packages/geopy/geocoders/base.py", line 158, in _call_geocoder 
    raise GeocoderTimedOut('Service timed out') 
    geopy.exc.GeocoderTimedOut: Service timed out 

預先感謝您!

+1

您正在捕獲錯誤異常;你需要捕捉的異常是'GeocoderTimedOut'。 –

回答

15

試試這個:

from geopy.geocoders import Nominatim 
from geopy.exc import GeocoderTimedOut 

my_address = '1600 Pennsylvania Avenue NW Washington, DC 20500' 

geolocator = Nominatim() 
try: 
    location = geolocator.geocode(my_address) 
    print location.latitude, location.longitude 
except GeocoderTimedOut as e: 
    print("Error: geocode failed on input %s with message %s"%(my_address, e.msg)) 

您還可以考慮增加超時的地理編碼叫你正在爲你的geolocator。在我的例子,將是這樣的:

location = geolocator.geocode(my_address, timeout=10) 

location = geolocator.geocode(my_address, timeout=None) 
+2

請注意,GeocoderTimedOut錯誤中'e'內的消息似乎是'.message'而不是'.msg' –

+0

.msg不起作用 –

1

,因爲你試圖多次要求該地址,他們暫時封鎖你或減慢你失望你可能會遇到這個問題,因爲他們的usage policy。它表示沒有更多的請求比每秒一個,並且你應該緩存你的結果。我遇到了這個問題,你有幾個解決方案。如果你不想更改你的代碼,你可以得到一個Google API密鑰,你可以免費使用2500個請求,或者你可以緩存你的結果。因爲我已經在AWS上使用DynamoDB解決了我的問題,所以我繼續創建了一個表,可以將結果緩存起來。Here is the gist of my code.