隐式等待在显式等待之后执行

2024-09-27 00:14:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用selenium+python unittest的自动脚本时遇到问题。 在我的设置()中,我有一行:

def setUp(self):
  self.driver.implicitly_wait(10)

在我的一个pageobjects中,我有一个方法:

    def return_note_asunto(self):
      WebDriverWait(self.driver, 5).until(EC.invisibility_of_element_located(self.gw_loader))
      WebDriverWait(self.driver, 5).until(EC.presence_of_element_located(self.note_asunto))
      return self.driver.find_elements(*self.note_asunto)[0].text

方法中的第一个显式等待等待加载程序在页面上不可见。当这种情况发生时,隐式等待执行,脚本在加载程序解除后10秒停止,然后脚本继续运行。 我不知道为什么隐式等待会在加载程序解除后执行,知道为什么会发生这种情况吗?根据我的理解,在测试失败之前,隐式等待对象x秒

谢谢


Tags: of方法self程序脚本returndefdriver
1条回答
网友
1楼 · 发布于 2024-09-27 00:14:25

你们很接近你们对隐性等待的期望,但还有一点

根据selenium docs wait页:

By implicitly waiting, WebDriver polls the DOM for a certain duration when trying to find any element

因此,当试图查找任何元素时,它都在等待。这设置一次并影响每个webdriver操作

要了解您正在经历的行为,您需要查看预期情况

转到github源代码,在python expected conditions中有以下内容:

def invisibility_of_element_located(locator):
    """ An Expectation for checking that an element is either invisible or not
    present on the DOM.
    locator used to find the element
    """
    def _predicate(driver):
        try:
            target = locator
            if not isinstance(target, WebElement):
                target = driver.find_element(*target)
            return _element_if_visible(target, False)
        except (NoSuchElementException, StaleElementReferenceException):
            # In the case of NoSuchElement, returns true because the element is
            # not present in DOM. The try block checks if the element is present
            # but is invisible.
            # In the case of StaleElementReference, returns true because stale
            # element reference implies that element is no longer visible.
            return True

    return _predicate

这是有问题的一行:target = driver.find_element(*target)

当执行find_element时,对象不存在(因为您希望元素不存在),隐式等待会导致它等待10秒,然后抛出NoTouchElement并最终返回true

向前看,你可能有几个选择

首先,不要同时使用两种等待策略。selenium文档确实说:

Warning: Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example, setting an implicit wait of 10 seconds and an explicit wait of 15 seconds could cause a timeout to occur after 20 seconds.

这不是一个很好的选择。但是,仔细想想——如果您有一个隐式等待,它将等待对象2准备就绪,那么您是否需要等待对象1消失

另一个选项是,将等待包装在自己的函数中,并在隐式等待之前将隐式等待设置为零,然后在退出时将其设置为10。这是很多假货,但它可以工作。 我手头没有IDE,但如果你需要支持让这个想法发挥作用,请告诉我一声

相关问题 更多 >

    热门问题