Program ended without completing the task

ぃ、小莉子 提交于 2019-12-24 18:39:43

问题


When I run my script, it is ended before completing the task that is in while loop.

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")

As my site is not having the element it should always print Error, but when I run my code it prints Error only once (though it is checked in while loop).

What I exactly need: The script should check whether the element is there or not till the element is there, and then run the rest code.


回答1:


Your code has an obvious flaw in logic:

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

You've defined s_b_c_status as "False", so your while loop will not do even a single iteration...

If you need to wait for element to appear in DOM, try to implement 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")


来源:https://stackoverflow.com/questions/52118767/program-ended-without-completing-the-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!