【问题标题】:Import api url data more than 10 000 rows with Python使用Python导入超过10 000行的api url数据
【发布时间】:2021-04-07 05:34:25
【问题描述】:

我尝试导入一个 json url (api),该文件有 "nhits":20843

这是我的网址:https://opendata.reseaux-energies.fr/api/records/1.0/search/?dataset=injections-regionales-quotidiennes-consolidees-rpt&q=&rows=20843&facet=date&facet=region&facet=filiere&facet=plage_de_puissance

这是我的代码:

import requests
site = "https://opendata.reseaux-energies.fr/api/records/1.0/search/?dataset=injections-regionales-quotidiennes-consolidees-rpt&q=&rows=20843&facet=date&facet=region&facet=filiere&facet=plage_de_puissance"
r = requests.get(site)
data = r.json()

我有一条错误消息:

'raw_params': {'expected': '-1 <= rows <= 10000', 'field_value': 20843, 'field_name': 'rows'}, 'raw_message': 'Invalid field in API request: {field_name} with value {field_value}. Expected: {expected}', 'error_key': 'InvalidFieldInAPIRequestExpectedException'}

如何避免错误

ps:对不起我的英语不好

【问题讨论】:

  • 看起来您一次最多只能请求 10000 行。所以你必须请求前 10000 个,然后是下一个 10000,最后是 843 个。

标签: python json api


【解决方案1】:

您一次请求多个结果。该错误表明您一次只能请求 10K 个结果。因此,如果您想获得每一个结果,则需要将您的请求分成多个部分。

对于我的代码,我将每个请求的结果减少到 1000,这样请求就不会超时。然后对于每个后续请求,我通过将 start=" + str(i) + "&amp; 添加到 url 来增加您的 api 的起始参数。请参阅文档https://help.opendatasoft.com/apis/ods-search-v1/#available-apis

import requests
import math
datas = []
for i in range(math.ceil(20843/1000)):
    site = "https://opendata.reseaux-energies.fr/api/records/1.0/search/?dataset=injections-regionales-quotidiennes-consolidees-rpt&q=&rows=1000&start="+str(i*1000)+"&facet=date&facet=region&facet=filiere&facet=plage_de_puissance"
    r = requests.get(site)
    datas.append(r.json())

【讨论】:

  • 感谢@JohnGordon,刚刚修复了一个关于缺少&amp; 的错误。我已经验证它现在可以工作了。
猜你喜欢
  • 2017-02-09
  • 2021-06-26
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多