【问题标题】:Python append json to json file in a while loopPython在while循环中将json附加到json文件
【发布时间】:2015-06-09 23:17:36
【问题描述】:

我正在尝试使用 Python Requests 库从 GitHub API 获取所有用户信息。这是我的代码:

import requests
import json

url = 'https://api.github.com/users'
token = "my_token"
headers = {'Authorization': 'token %s' % token}

r = requests.get(url, headers=headers)
users = r.json()
with open('users.json', 'w') as outfile:
    json.dump(users, outfile)

我现在可以将用户的第一页转储到一个 json 文件中。我还可以找到“下一页”的网址:

next_url = r.links['next'].get('url')
r2 = requests.get(next_url, headers=headers)
users2 = r2.json()

由于我还不知道有多少页,我怎样才能在 while 循环中尽可能快地将第 2、第 3... 页按顺序附加到“users.json”?

谢谢!

【问题讨论】:

    标签: python json python-requests github-api writefile


    【解决方案1】:

    首先,你需要以'a'模式打开文件,否则子序列写入会覆盖所有内容

    import requests
    import json
    
    url = 'https://api.github.com/users'
    token = "my_token"
    headers = {'Authorization': 'token %s' % token}
    
    outfile = open('users.json', 'a')
    
    while True:
        r = requests.get(url, headers=headers)
        users = r.json()
        json.dump(users, outfile)
        url = r.links['next'].get('url')
        # I don't know what Github return in case there is no more users, so you need to double check by yourself
        if url == '':
            break
    
    outfile.close()
    

    【讨论】:

    • 非常感谢! GitHub API 的速率限制为 5000 个请求/小时。按照您的回答,在上一次运行因限制停止后,如何在新运行中继续写入文件?
    • 您应该在每个请求后添加time.sleep(1)
    【解决方案2】:

    将从requests 查询中获得的数据附加到一个列表中,然后继续下一个查询。

    获得所需的所有数据后,继续尝试将数据连接到文件或对象中。您也可以使用threading 并行执行多个查询,但很可能会对 api 进行速率限制。

    【讨论】:

    • 感谢您的回答。我只能用工作代码标记那个。您的建议绝对正确。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 2020-12-31
    • 2021-08-28
    相关资源
    最近更新 更多