在python中为特定json元素轮询api

问题描述 投票:0回答:1

我正在从具有json响应的api请求数据。 json内容一直在动态变化。我希望我的python脚本持续运行,例如每5秒查看json,直到给定的语句为true,这可能是当json响应中存在给定的用户ID号时。当存在用户ID号时,请执行操作,例如在json响应中也找到print userid和连接的用户名。

我一直在看polling documentation,但我不知道如何以自己想要的方式使用它。

我不会每5秒钟对data['result']['page']['list']轮询一次['user_id'],并且当['user_id']为True时,请打印连接到与用户ID相似的信息,例如昵称。

response = requests.post('https://website.com/api', headers=headers, data=data)

json_data = json.dumps(response.json(), indent=2)
data = json.loads(json_data)

userid = input('Input userID: ')


for ps in data['result']['page']['list']:
    if userid == str(ps['user_id']):
        print('Username: ' + ps['nick_name'])
        print('UserID: ' + str(ps['user_id']))
python json python-3.x polling
1个回答
0
投票

一个简单的循环呢?

import time

userid = input('Input userID: ')

while True:
 response = requests.post('https://website.com/api', headers=headers, data=data)
 json_res = response.json()
 for ps in json_res['result']['page']['list']:
    if userid == str(ps['user_id']):
        print('Username: ' + ps['nick_name'])
        print('UserID: ' + str(ps['user_id']))
        break
 time.sleep(5)
© www.soinside.com 2019 - 2024. All rights reserved.