我正在尝试使用Python请求Google Places API,在给定半径内获取特定位置类型为餐厅的所有地点。以下是我的简单代码:
import requests
import json
APIKEY = "AIzaSyBFx8hqftDOlrSWRTiOSowjwfeS1OQtBpw"
def findPlaces(loc=("51.1079","17.0385"),radius=3000, pagetoken = None):
lat, lng = loc
type = "restaurant"
url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={lat},{lng}&radius={radius}&type={type}&key={APIKEY}{pagetoken}".format(lat = lat, lng = lng, radius = radius, type = type,APIKEY = APIKEY, pagetoken = "&pagetoken="+pagetoken if pagetoken else "")
print(url)
response = requests.get(url)
res = json.loads(response.text)
print(res)
for result in res["results"]:
info = ";".join(map(str,[result["name"],result["geometry"]["location"]["lat"],result["geometry"]["location"]["lng"],result.get("rating",0),result["place_id"]]))
print(info)
pagetoken = res.get("next_page_token",None)
return pagetoken
pagetoken = None
while True:
pagetoken = findPlaces(pagetoken=pagetoken)
if not pagetoken:
break
然而,虽然它对于结果的第一页运行良好,但在进入第二页时失败了,没有明显的原因(它只是从API返回无效请求)。此外,有趣的是,由于我将我的网址打印到控制台上,我可以通过单击它来跟踪这个非常特定的网址,当我这样做时,它完美地工作,API返回所需的餐厅列表。
我以为这是一个关于编码url字符串的问题,所以我用Python的urlencode替换了格式,但结果仍然相同。由于我没有更多的想法,我想问一下:有人遇到过这样的问题吗?
提前感谢任何帮助。