[英]Making ten api calls through a loop
An API I want to use limits requests to 10 items. 我要使用的API将请求限制为10个项目。 I want to download 100 items.
我想下载100个项目。 I am trying to write a function that makes 10 API, using their offset functionality to make it possible.
我正在尝试编写一个使10 API成为可能的函数,并使用其偏移功能来实现。 I figured a loop would be the proper way to do this.
我认为循环将是执行此操作的正确方法。
This is the code I have, but it doesn't work and I don't understand why: 这是我的代码,但是它不起作用,我也不明白为什么:
import pandas as pd
import requests
api_key = 'THIS_IS_MY_KEY'
api_url = 'http://apiurl.com/doc?limit=10' # fake url
headers = {'Authorization': 'Bearer ' + api_key}
for x in range(0, 10):
number = 0
url = api_url + '&offset=' + str(number + 10)
r = requests.get(url, headers=headers)
x = pd.DataFrame(r.json())
x = x['data'].apply(pd.Series)
return x
You are also using x as your loop counter and as your data frame - which i think is not good practice - although your code might still work because of the way that the for loop works. 您还使用x作为循环计数器和数据帧-我认为这不是一个好习惯-尽管由于for循环的工作方式,您的代码仍然可以工作。 A better is to use the step parameter in the range call - as demonstrated below.
更好的方法是在范围调用中使用step参数-如下所示。 It is also not clear what you are expecting to return - are you wanting to return the last offset you fetched - or the the data frame (since your code re-uses x in 3 different ways it is impossible to determine what you intended - so I left it as it is - although I am pretty sure it is wrong - looking at the panda API)
还不清楚您期望返回什么-您是否要返回获取的最后一个偏移量-还是数据帧(由于代码以3种不同的方式重复使用x,因此无法确定您的意图-因此我照原样保留了它-尽管我非常确定这是错误的-看看panda API)
import pandas as pd
import requests
api_key = 'THIS_IS_MY_KEY'
api_url = 'http://apiurl.com/doc?limit=10' # fake url
headers = {'Authorization': 'Bearer ' + api_key}
for offset in range(0, 100, 10): # makes a list [0, 10,20,30,40,50,60,70,80,90,100]
url = api_url + '&offset=' + str(offset)
r = requests.get(url, headers=headers)
x = pd.DataFrame(r.json())
x = x['data'].apply(pd.Series)
return x
what result do you see? 您看到什么结果? try
尝试
url = api_url + '&offset=' + str(x * 10)
The variable number never change, since it is set to 0 at the start of the loop. 变量号从不更改,因为在循环开始时将其设置为0 。
I think you means this: 我认为您的意思是:
import pandas as pd
import requests
api_key = 'THIS_IS_MY_KEY'
api_url = 'http://apiurl.com/doc?limit=10' # fake url
headers = {'Authorization': 'Bearer ' + api_key}
number = 0
for x in range(0, 10):
url = api_url + '&offset=' + str(number + 10)
r = requests.get(url, headers=headers)
x = pd.DataFrame(r.json())
x = x['data'].apply(pd.Series)
number += 10
return x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.