如何捕获地理编码循环中的错误并继续循环

时间:2018-04-01 11:49:54

标签: python

我是python的新手,像往常一样,我遇到了麻烦。我正在尝试使用循环将api.geocode(place)的结果存储到列表location,但是当找不到该位置的匹配时,循环停止。这是一个最小的例子。

from gmaps import Geocoding
api = Geocoding(api_key = 'API Key')
address = ["Philippines", "Canada", "No place like this, Australia", "Malaysia"]
location = []
for place in address:
    location.append(api.geocode(place))

这会抛出此错误:

Traceback (most recent call last):

  File "<ipython-input-54-8a375b31e18c>", line 2, in <module>
    location.append(api.geocode(place))

  File "/home/quack/anaconda3/lib/python3.6/site-packages/gmaps/geocoding.py", line 37, in geocode
    return self._make_request(self.GEOCODE_URL, parameters, "results")

  File "/home/quack/anaconda3/lib/python3.6/site-packages/gmaps/client.py", line 89, in _make_request
    )(response)

NoResults: {'results': [], 'status': 'ZERO_RESULTS', 'url': 'https://maps.googleapis.com/maps/api/geocode/json?address=No+place+like+this%2C+Australia&sensor=false&key=AIzaSyA-lk2z3VIZuKAq27ooswFPqjIKUDlMC2M'}

我尝试使用tryexcept解决方案,如下所示:

for place in address:
    try:
        location.append(api.geocode(place))
    except:
        pass

这会得到长度为3的列表location。我如何指示NoResult代替No place like this, Australia的结果并继续循环?

2 个答案:

答案 0 :(得分:2)

如果我理解你的问题:

from gmaps import Geocoding
api = Geocoding(api_key = 'API Key')
address = ["Philippines", "Canada", "No place like this, Australia", "Malaysia"]
location = []
for place in address:
    try:
        location.append(api.geocode(place))
    except Exception as e:
        location.append("No Result")

但更好的方法是:

from gmaps import Geocoding
api = Geocoding(api_key = 'API Key')
address = ["Philippines", "Canada", "No place like this, Australia", "Malaysia"]
location = {}
for place in address:
    try:
        location[place] = api.geocode(place)
    except Exception as e:
        location[place] = "No Result"

建立一个字典,你可以看到哪些地方不存在。

答案 1 :(得分:1)

您可以将引发的NoResults例外添加到location列表中。

for place in address:
    try:
        location.append(api.geocode(place))
    except Exception as exc:
        location.append(exc)