【发布时间】:2021-05-23 06:26:30
【问题描述】:
我有一个问题:如果“while”开始并且第一个条件为“false”,即使“if”变为“true”,它也会继续变为“else”,我需要留在循环中但停止 if 语句开始循环所有 if 语句,我希望我清楚地解释了这个问题,我尝试了 break()、pass() 和 continue(),它们都停止了循环。
CurrentTime = datetime.now().time()
Actual_Time = CurrentTime.strftime("%H:%M")
Static_Time = '15:54'
while True:
print('Teeest Looop')
if (Actual_Time == Static_Time) :
print('Teeest')
options = Options()
options.add_argument("--user-data-dir=chrome-data")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome('C:\\Users\\hana\\Downloads\\chromedriver_win32\\chromedriver.exe', options=options)
driver.maximize_window()
driver.get('https://web.whatsapp.com')
time.sleep(20)
driver.find_element_by_xpath("//*[@title='hana']").click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="main"]/footer/div[1]/div[2]/div/div[2]'))).send_keys('test sending')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='_2Ujuu']"))).click()
time.sleep(10)
driver.close()
elif (Actual_Time != Static_Time) :
print('Not lucky time')
【问题讨论】:
-
你确定缩进吗?看起来您没有在 while 循环中放置缩进。
-
是的,我确定,但是当我在这里复制代码时它已经改变了
-
@Hana 我没有看到 for 循环,也没有看到
break、continue、pass中的任何一个。你在哪里尝试这样做?你想做什么,发生了什么? -
continue 效果很好,我猜你试过
continue()只使用continue -
@Hana,仍然不太明白问题出在哪里,但我可以猜到。您在 while 循环之外设置时间。然后你进入循环,除非时间实际上是 15:54,否则你总是会一遍又一遍地执行 else 条件。如果您希望它在一次迭代后停止,请不要将其放入 while 循环中,或者添加
break。如果你想让一些不同的事情发生,你需要在 while 循环中设置Actual_Time。
标签: python if-statement while-loop break