首页 > 解决方案 > 程序没有完成任务就结束了

问题描述

while当我运行我的脚本时,它会在完成循环中的任务之前结束。

driver = webdriver.Chrome()
driver.get('http://example.com')
#input("Press any key to continue1")
s_b_c_status = "False"
while s_b_c_status == "True":
    try:
        if(driver.find_element_by_xpath("//div[@role='button' and @title='Status']")):
            s_b_c_status = "True"
    except NoSuchElementException:
        s_b_c_status = "False"
if(s_b_c_status == "True"):
    print("Scanning Done!")
else:
print("Error")

由于我的网站没有它应该始终打印的元素Error,但是当我运行我的代码时它只打印Error一次(尽管它是在while循环中检查的)。

我到底需要什么: 脚本应该检查元素是否存在,直到元素存在,然后运行其余代码。

标签: python-3.xloopsseleniumwhile-loop

解决方案


您的代码在逻辑上有明显缺陷:

s_b_c_status = "False"
while s_b_c_status == "True"

您已定义s_b_c_status"False",因此您的while循环甚至不会进行一次迭代...

如果您需要等待元素出现在 DOM 中,请尝试实现ExplicitWait

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

driver = webdriver.Chrome()
driver.get('http://example.com')

try:
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@role='button' and @title='Status']")))
except TimeoutException:
    print("Element not found")

推荐阅读