我正在通过 json 响应从 api 请求数据。 json内容一直在动态变化。我希望我的 python 脚本能够连续运行并查看 json,例如每 5 秒一次,直到给定的语句为 true,这可能是在 json 响应中出现给定的用户 ID 号时。 当用户 ID 号存在时,然后执行操作,例如打印用户 ID,并且在 json 响应中也找到了连接的用户名。
我一直在看polling documentation但我不知道如何按照我想要的方式使用它。
我不想每 5 秒轮询一次 data['result']['page']['list']
来查找 ['user_id']
['user_id']
为 True,则打印与 user_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']))
最佳答案
简单的循环怎么样?
import time
found_occurrence = False
userid = input('Input userID: ')
while not found_occurrence:
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']))
found_occurrence = True
time.sleep(5)
如果您想让它连续运行,您可以无限循环(直到中断)并将事件记录到如下文件中:
import logging
import time
import sys
logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
userid = input('Input userID: ')
try:
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']):
logging.info('Username: ' + ps['nick_name'])
logging.info('UserID: ' + str(ps['user_id']))
time.sleep(5)
except KeyboardInterrupt:
logging.info("exiting")
sys.exit()
关于python - 在 python 中轮询 api 以获取特定的 json 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59091758/