Geopy:捕获超时错误

26
我正在使用geopy对一些地址进行地理编码,希望能捕获超时错误并将其打印出来,以便我可以对输入进行质量控制。我尝试使用try/catch语句包装geocode请求,但似乎并没有起作用。请问我需要怎么做?
以下是我的代码:
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 - Burhan Khalid
4个回答

44

试试这个:

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.message))

你也可以考虑增加你的地理定位器调用的超时时间。在我的示例中,它应该是这样的:

location = geolocator.geocode(my_address, timeout=10)
或者
location = geolocator.geocode(my_address, timeout=None)

4
注意,GeocoderTimedOut错误中e里的信息似乎现在是.message而不是.msg - Shane Reustle

7

我处理了同样的问题很多天,这是我的代码:

geolocator = Nominatim(user_agent="ny_explorer")
location = geolocator.geocode(address_venue)

错误 服务超时

解决方案:添加一个新的属性来声明超时时间:

location = geolocator.geocode(address_venue,timeout=10000)

5
您可能遇到了这个问题,因为您尝试多次请求此地址,他们暂时阻止了您或减慢了您的速度,因为他们的使用政策。它规定每秒不超过一个请求,并且您应该缓存您的结果。我也遇到了这个问题,您有几个解决方案。如果您不想太多更改代码,您可以获得一个Google API密钥,可以免费使用每天2500个请求,或者您可以缓存您的结果。因为我已经在AWS上使用DynamoDB解决我的问题,所以我创建了一个表来缓存我的结果。这是我的代码要点。

0
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent='xyz', timeout=200)

添加超时时间将解决这个问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接