如何从此web服务下载多页数据?

2024-04-26 19:02:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

1000名候选人是一次申请允许的限制,但肯定还有更多。我想知道怎样才能得到下一页的结果。根据他们自己的文件:

To download all representatives, send a request to https://represent.opennorth.ca/representatives/?limit=1000 and follow the next link under the meta field until you reach the end. We host the shapefiles and postal code concordances on GitHub.

这是针对“代表”的数据,但我假设“候选人”也是如此。我不明白他们所说的“跟随元域下的下一个链接直到你到达终点”是什么意思。有人能告诉我这件事吗?你知道吗

这是我目前的剧本:

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")

Tags: andthe数据httpsurlrequestallurllib
1条回答
网友
1楼 · 发布于 2024-04-26 19:02:02

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

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

你需要的链接是["meta"]["next"]。你知道吗

或者,您可以通过添加offsetURL参数来构建该链接。你知道吗

相关问题 更多 >