问题
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