我正在从带有json响应的api请求数据。json内容一直在动态变化。我希望我的python脚本持续运行,例如每5秒查看json,直到给定的语句为true,这可能是当json响应中存在给定的用户ID号时。当存在用户标识号时,请执行操作,例如在json响应中也找到print用户标识和连接的用户名。
我一直在查看投票文档,但无法弄清楚如何以自己想要的方式使用它。
我wan't投票data['result']['page']['list']
为['user_id']
每5秒,当['user_id']
为真,则打印连接到像NICK_NAME 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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句