我正在从一个带有json响应的api请求数据。json内容一直在动态变化。我希望我的python脚本连续运行并查看json,例如每隔5秒查看一次,直到给定的语句为真,这可能是当给定的userid号出现在json响应中时。当用户is号存在时,执行一个操作,例如打印在json响应中也可以找到的userid和连接的用户名。
我一直在研究polling documentation,但我不知道如何使用它。
我不想每5秒轮询一次['user_id']
的data['result']['page']['list']
,当['user_id']
为True时,然后像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']))
发布于 2019-11-28 23:18:25
那么一个简单的循环呢?
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()
https://stackoverflow.com/questions/59091758
复制相似问题