python - 我怎样才能摆脱循环?
问题描述
所以我一直在尝试使用监视器 - 对于那些不知道什么是监控的人 - 基本上这意味着你正在检查某些东西等元素,网址或其他任何东西,然后再次检查它是否已经改变了。
这就是我所做的,并且...
url = 'mrcnoir'
while True:
try:
password_page = requests.get('https://{}.com'.format(url), timeout=5)
password_page.raise_for_status()
except requests.exceptions.RequestException as err:
print('Error checking password page! - https://{}.com'.format(url) + ' - ' + str(err))
continue
else:
# *************---If password up---**************
if ('password' in password_page.url):
# Password page is up
print('Password page is up! - ' + 'https://{}.com'.format(url))
if not ('password' in password_page.url):
# No password page -> password page
# *************---Send---**************
print("SENDING...1")
time.sleep(random.randint(6, 12))
# *************---If password down---**************
else:
# Password page is down
print('Password page is down! - ' + 'https://{}.com'.format(url))
if ('password' in password_page.url):
# Password page -> no password page
# *************---Send---**************
print("SENDING...2") #<---- If it comes in here - it will be stuck forever and just keep posting this print...
time.sleep(random.randint(6, 12))
# *************---Retry between 6-12 random.---**************
finally:
time.sleep(random.randint(6, 12))
我遇到的问题是在底部打印“SENDING...2”-发生的事情是它一直在继续打印 SENDING...2,这意味着它被困在循环中-
基本上我想要做的是,每当涉及到第二个 Else 部分时,它应该打印一次,然后继续“监控”并检查直到有新的变化。这意味着它将需要等到它出现在 URL 中/密码。
在那种情况下,我怎么能做到这一点?
解决方案
url = 'mrcnoir'
last_status = False
while True:
try:
password_page = requests.get('https://{}.com'.format(url), timeout=5)
password_page.raise_for_status()
except requests.exceptions.RequestException as err:
print('Error checking password page! - https://{}.com'.format(url) + ' - ' + str(err))
continue
else:
# *************---If password up---**************
if 'password' in password_page.url and last_status == False:
# Password page is up
last_status = True
print('Password page is up! - ' + 'https://{}.com'.format(url))
time.sleep(random.randint(6, 12))
# *************---If password down---**************
elif not 'password' in password_page.url and last_status == True:
# Password page is down
last_status = False
print('Password page is down! - ' + 'https://{}.com'.format(url))
time.sleep(random.randint(6, 12))
# *************---Retry between 6-12 random.---**************
finally:
time.sleep(random.randint(6, 12))
推荐阅读
- javascript - 如何将javascript函数链接到按钮?
- python - 检测到 Python Ubuntu pypxlib 堆栈粉碎
- android - Android 通知:数据和消息
- javascript - 获取对象数组中的特定数据并删除其行(条带化谷歌应用脚本)
- amazon-web-services - 如何将特定文件夹从 AWS S3 挂载到 ec2 实例
- flutter - 如何在flutter默认日期选择器小部件中删除时间戳并仅从日期选择器中获取日期
- jquery - Kendo UI:标签条内的网格标题(宽度)对齐问题
- regex - .htaccess 重写正则表达式:匹配任何内容,但不得影响其他规则
- java - 如何在java中查看exe的退出状态
- latex - 如何使用 doxygen 生成带有自定义乳胶样式表和命令的 pdf?