请求API但返回空,为什么?

时间:2020-01-07 17:22:24

标签: python pandas api request

搜索了各种方法,没有用,不知道哪一部分出了错。

它只能使用一次,如何循环访问ID列表,某些ID可能返回错误,因此会被跳过。

当前代码

x = 22555003
URL = "https://data.gcis.nat.gov.tw/od/data/api/5F64D864-61CB-4D0D-8AD9-492047CC1EA6?$format=json&$filter=Business_Accounting_NO eq {}".format(x)
response = requests.get(url = URL)
data = response.json()
result = pd.DataFrame(data)
result.head()

希望输出但出错

listID = ['22555003','12345678','27240313']
#12345678 is error ID
result = []
for x in listID:
    try:
        JSONContent = requests.get("https://data.gcis.nat.gov.tw/od/data/api/5F64D864-61CB-4D0D-8AD9-492047CC1EA6?$format=json&$filter=Business_Accounting_NO eq {}".format(x)).json()
        result.append([JSONContent['Business_Accounting_NO'],
                       JSONContent['Capital_Stock_Amount']])
    except:
        pass

dataset = pd.DataFrame(result)
dataset.head()

为什么结果为空? 谢谢!!!

1 个答案:

答案 0 :(得分:1)

import pandas as pd
import requests



listID = ['22555003','12345678','27240313']
#12345678 is error ID
result = []
for x in listID:
    try:
        JSONContent = requests.get("https://data.gcis.nat.gov.tw/od/data/api/5F64D864-61CB-4D0D-8AD9-492047CC1EA6?$format=json&$filter=Business_Accounting_NO eq {}".format(x)).json()
        #print(JSONContent[0]['Business_Accounting_NO'])
        result.append([JSONContent[0]['Business_Accounting_NO'],JSONContent[0]['Capital_Stock_Amount']])
        print(result)
    except Exception as e:
        print(e)
dataset = pd.DataFrame(result)
dataset.head()
print(result)