使用 Google 距离矩阵 API 和 Python 时出错

Error using Google distance matrix API with Python

这是我的代码:

from googlemaps import Client as GoogleMaps
mapServices = GoogleMaps('')
start = 'texarkana'
end   = 'atlanta'
direction = mapServices.directions(start, end)
for step in direction['Direction']['Routes'][0]['Steps']:
    print(step['descriptionHtml'])

我收到以下错误:

File "C:\Python27\directions.py", line 7, in <module>
for step in direction['Direction']['Routes'][0]['Steps']:
TypeError: list indices must be integers, not str

我无法帮助您直接查明错误,因为我没有 API 密钥来亲自尝试。但是,我可以给你一些东西,你可以尝试并考虑找到问题的根源。

您的 for 循环 (for step in direction['Direction']['Routes'][0]['Steps']:) 中的索引之一似乎应该是一个整数。

您可以尝试使用内置的 type() 函数找出哪个。所以要调试,我会尝试:type(direction),然后是 type(direction['Direction']) 等等,但 direction['Direction']['Routes'] 除外,因为它已经是一个列表。

我建议您为此使用交互式 python 解释器。您要寻找的是当您输入代码(例如 type(direction))时,您会得到 type<'list'>

找出罪魁祸首后,也许您可​​以对其进行索引并找到您想要的或阅读 Google Docs