【问题标题】:Program ended without completing the task程序没有完成任务就结束了
【发布时间】:2019-02-06 16:22:00
【问题描述】:

当我运行我的脚本时,它在完成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 循环中进行了检查)。

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

【问题讨论】:

  • 元素出现通常需要等待多长时间?
  • 10-20秒之间,我不想在这里使用time.sleep()...
  • @Rabe 我认为 usecase 中存在一些混淆,正如您提到的my site is not having the element it should always print Error 但后来您提到了check whether the element is there or not till the element is there,所以主要问题是该元素是那里?如果是这样,您对元素的下一个粗略操作是什么?解决方案将取决于该条件。
  • 元素100%肯定会存在,但它会出现多少时间后并不固定,因为它会根据用户的互联网速度...
  • @Rabe 好的,您对元素的下一个粗略操作是什么? 检索某些属性(例如text)或调用click()

标签: python-3.x loops selenium while-loop


【解决方案1】:

你的代码有明显的逻辑缺陷:

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

【讨论】:

  • 20 是什么意思?它会检查到 20 秒或 20 秒后?另外,如果 20 秒内没有找到,我们如何发送消息?
  • @Rabe ,这意味着 等待元素出现在 DOM 中最多 20 秒。如果元素没有出现,TimeoutException 将被提升。检查更新的答案
  • 如果元素在 2 秒内找到,那么它也会等待 20 秒还是在 2 秒后继续?
  • @Rabe 2 秒后继续
  • 如果我也能通过while 循环获得解决方案,我将不胜感激,以供我将来参考...
猜你喜欢
  • 2021-04-03
  • 2015-04-26
  • 1970-01-01
  • 2018-05-07
  • 1970-01-01
  • 1970-01-01
  • 2016-01-01
  • 1970-01-01
  • 2021-09-16
相关资源
最近更新 更多