2015-01-13 77 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.