在for循环python中更改API调用

时间:2018-06-08 15:34:18

标签: python api loops dataframe

我试图在for循环中调用几个api数据集以更改调用,然后将这些数据集附加到一个更大的数据帧中。

我编写了这段代码,用于调用第一个数据集,然后在下次调用时返回此错误。

`url = base + "max=" + maxrec + "&" "type=" + item + "&" + "freq=" + freq + "&" + "px=" +px + "&" + "ps=" + str(ps) + "&" + "r="+ r + "&" + "p=" + p + "&" + "rg=" +rg + "&" + "cc=" + cc + "&" + "fmt=" + fmt

TypeError: must be str, not Response`

这是我目前的代码

import requests
import pandas as pd

base = "http://comtrade.un.org/api/get?"
maxrec = "50000"
item = "C"
freq = "A"
px="H0"
ps="all"
r="all"
p="0"
rg="2"
cc="AG2"
fmt="json"

comtrade = pd.DataFrame(columns=[])

for year in range(1991,2018):
    ps="{}".format(year)
    url = base + "max=" + maxrec + "&" "type=" + item + "&" + "freq=" + freq + "&" + "px=" +px + "&" + "ps=" + str(ps) + "&" + "r="+ r + "&" + "p=" + p + "&" + "rg=" +rg + "&" + "cc=" + cc + "&" + "fmt=" + fmt
    r = requests.get(url)
    x = r.json()
    new = pd.DataFrame(x["dataset"])
    comtrade = comtrade.append(new)

2 个答案:

答案 0 :(得分:1)

requests为您汇总网址。

common_params = {
    "max": maxrec,
    "type": item,
    "freq": freq,
    # etc
}

for year in range(1991,2018):    
    response = requests.get(base, params=dict(common_params, ps=str(year))
    response_data = response.json()
    new = pd.DataFrame(response_data["dataset"])
    comtrade = comtrade.append(new)

答案 1 :(得分:0)

免责声明:另一个答案是正确的,您应该使用它。

但是,您的实际问题源于您在此处覆盖r的事实:

r = requests.get(url)
x = r.json()

在下一次迭代中,r仍将是该值,而不是您首先初始化它的值。您可以简单地将其重命名为结果以避免该问题。最好让请求库完成工作。