我正在尝试下载2015年加拿大联邦选举所有候选人的数据。有一项名为opennorth的服务,该服务具有一个API,您可以通过向此url发送请求来执行此操作:

https://represent.opennorth.ca/candidates/?limit=1000

一个请求中允许有1000个候选人,但肯定还有更多。我想知道如何获得下一页结果。从他们自己的文档中:


  要下载所有代表,请发送请求至
  https://represent.opennorth.ca/representatives/?limit=1000并关注
  元字段下的下一个链接,直到到达末尾。我们主持
  GitHub上的shapefile和邮政编码规范。


这是针对“代表”数据的,但是我认为“候选人”是相同的。我不理解“跟随元字段下的下一个链接直到到达结尾”的含义。有人可以启发我吗?

到目前为止,这是我的脚本:

import urllib

with urllib.request.urlopen(r"https://represent.opennorth.ca/candidates/house-of-commons/?limit=1000") as url:
    with open(r"F:\electoral_map\candidates_python\candidates.js", "wb+") as f:
        f.write(url.read())
print("all done")

最佳答案

在返回的JSON对象中,有一个名为meta的对象。

..."meta": {"next": "/representatives/?limit=1000&offset=1000",
            "total_count": 2140,
            "previous": null,
            "limit": 1000,
            "offset": 0}}


您需要的链接是["meta"]["next"]中的链接。

或者,您可以通过添加offset URL参数来构建该链接。

09-25 16:15
查看更多