首页 > 解决方案 > 如果语句不在python中循环,如何停止?

问题描述

我有一个问题:如果'while'开始并且第一个条件'false'它会继续'else',即使'if'变成'true',我需要留在循环中但停止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') 

标签: pythonif-statementwhile-loopbreak

解决方案


您正在设置永远不会在while循环外更改的值,然后您永远不会在循环内更新它们,因此if基于它们的 -condition 永远不会评估任何不同的值。

我想你想要类似的东西

from datetime import datetime

do_something_time = "15:54"

while True:
    current_time = datetime.now().strftime("%H:%M")
    if current_time == do_something_time:
        print("Doing something")  # this only prints at 15:54
    elif current_time == "00:00":
        break  # this exits the while loop at midnight
    else:
        print("Not this time!")

推荐阅读