Google Places API,如何获得下20个结果



这是我第一次使用Google Places API。我在Python中做了一个练习,试图从一个设定点获取20公里半径内的所有商店。

我可以毫无问题地获得前20个结果,但我不确定如何获得下20个结果。根据我在文档中阅读到的内容,我需要使用";next_page_token";,但我没能成功做到这一点。

这是我的测试代码:

url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=19.4196301,-99.16895&radius=20000&type=store&key=" + api_key
response = requests.get(url).json()
if response and response.get("status") == "REQUEST_DENIED":
print(response)
sys.exit(1)
elif response and response.get("status") != "ZERO_RESULTS":
print(json.dumps(response, indent=4, sort_keys=True))
print(len(response["results"]))
print(">>>> PAGE 1")
for result in response["results"]:
print("Store name: ", result["name"])
if "next_page_token" in response:
print(">>>> PAGE 2")
page2_token = response["next_page_token"]        
url_page_2 = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=19.4196301,-99.16895&radius=20000&type=store&pagetoken=" + page2_token + "&key=" + api_key
print(url_page_2)
response_page_2 = requests.get(url_page_2).json()
print(response_page_2)
for result in response_page_2["results"]:
print("Store name: ", result["name"])
else:
print("no next page")

当我的代码试图执行第二页的请求时,我不断收到以下错误消息:

{'html_attributions': [], 'results': [], 'status': 'INVALID_REQUEST'}

我不确定我在格式化第二页请求时做错了什么(甚至我做得正确(。有什么想法吗?

刚刚找到解决方案!当您获得下一个页面令牌时,您需要等待几秒钟才能获得下一页。不知怎的,如果你马上请求,代币信息还没有出现在谷歌服务器中。在请求之间添加一个简单的time.sleep(2(解决了这个问题。

对于下一页的结果,请尝试仅在url中设置pagetoken参数。删除所有其他参数。

pagetoken--从以前运行的搜索中返回最多20个结果。设置pagetoken参数将使用以前使用的相同参数执行搜索——除pagetoken之外的所有参数都将被忽略。

最新更新