如何使用Python的请求包访问API Get的特定元素?

时间:2019-08-08 11:15:36

标签: python json python-3.x response

嗨,我当前正在使用Python 3.X运行以下代码:

import requests

jurisdiction = 'us'

name = 'netflix'

limit = 1


r = requests.get('https://opencorporates.com/reconcile?query={%22query%22:%22' + name + '%22,%20%22limit%22:' + str(limit) + ',%20%22jurisdiction_code%22:%22' + jurisdiction + '%22}')

print(type(r))
print(r.text)

它的输出是

<class 'requests.models.Response'>

{"result":[{"id":"/companies/gb/12022722","name":"AMAZON-UK LIMITED","type":[{"id":"/organization/organization","name":"Organization"}],"score":69.0,"match":false,"uri":"https://opencorporates.com/companies/gb/12022722"}],"duration":157.957621}

我希望能够从响应中访问公司名称,然后将其添加到列表中。因此,我可以遍历一堆名称/辖区,并在末尾列出可以导出到csv(或其他格式)的列表。

我认为使用to.json或json.dump或类似的方法可能有效,但是我不确定到底该怎么做?如果需要,我愿意进口更多的包裹,例如熊猫等。

2 个答案:

答案 0 :(得分:1)

导入json,您可以读取如下公司名称:-

import json

data = json.loads(r.text)

#initialize your list 
namesList = []

for s in data['result']:
    name = s['name']
    namesList.append(name)

答案 1 :(得分:0)

您可以尝试一下。

data = {"result":[{"id":"/companies/gb/12022722","name":"AMAZON-UK LIMITED","type":[{"id":"/organization/organization","name":"Organization"}],"score":69.0,"match":False,"uri":"https://opencorporates.com/companies/gb/12022722"}],"duration":157.957621}


for i in data['result']:
    print(i['name'])