我正在使用以下 Python 代码通过 SODA API 提取数据
response = requests.get('https://healthdata.gov/resource/uqq2-txqb.json')
数据集包含 434,865 行,但当我使用 API 时,它只返回前 1,000 行。我在另一个问题上看到 $limit
可用于获取前 50,000 行,但如何将其与 $offset
结合起来获取所有 434,865 行?
** 我弄清楚了如何使用 $offset
现在有了结果代码,有什么方法可以压缩它吗?
response1 = requests.get('https://healthdata.gov/resource/uqq2-txqb.json?$limit=50000')
response2 = requests.get('https://healthdata.gov/resource/uqq2-txqb.json?$limit=50000&$offset=50001')
response3 = requests.get('https://healthdata.gov/resource/uqq2-txqb.json?$limit=50000&$offset=100002')
response4 = requests.get('https://healthdata.gov/resource/uqq2-txqb.json?$limit=50000&$offset=150003')
response5 = requests.get('https://healthdata.gov/resource/uqq2-txqb.json?$limit=50000&$offset=200004')
response6 = requests.get('https://healthdata.gov/resource/uqq2-txqb.json?$limit=50000&$offset=250005')
response7 = requests.get('https://healthdata.gov/resource/uqq2-txqb.json?$limit=50000&$offset=300006')
response8 = requests.get('https://healthdata.gov/resource/uqq2-txqb.json?$limit=50000&$offset=350007')
response9 = requests.get('https://healthdata.gov/resource/uqq2-txqb.json?$limit=50000&$offset=400008')
最佳答案
这称为分页
,您可以在此处找到文档示例:https://dev.socrata.com/docs/paging.html
其中还指定了 API 有两个版本:
- v2.0,其中
$limit
最大可为 50,000 - v2.1,其中
$limit
不受限制
您使用的端点似乎支持 v2.1,至少基于此 https://dev.socrata.com/foundry/healthdata.gov/uqq2-txqb因此您应该能够为 $limit
使用较大的值并立即检索整个集合。
采用分页路由,$offset
值是基于 0
,因此您的查询应正确重写为:
response1 = requests.get('https://healthdata.gov/resource/uqq2-txqb.json?$limit=50000')
response2 = requests.get('https://healthdata.gov/resource/uqq2xqb.json?$limit=50000&$offset=50000')
response3 = requests.get('https://healthdata.gov/resource/uqq2xqb.json?$limit=50000&$offset=100000')
response4 = requests.get('https://healthdata.gov/resource/uqq2xqb.json?$limit=50000&$offset=150000')
注意 $limit
倍数的对齐方式。
关于python - 使用 $limit 和 $offset 在 SODA API 上获取超过 1,000 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71804530/