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'}

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

解决方法

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

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

,

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...