【问题标题】:Implicit wait is executing after an explicit wait隐式等待在显式等待之后执行
【发布时间】:2020-10-12 16:02:22
【问题描述】:

我在使用 selenium+python unittest 的自动化脚本时遇到问题。 在我的 setUp() 我有这一行:

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

在我的一个页面对象中,我有这个方法:

    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 秒等待对象。

谢谢!

【问题讨论】:

标签: python selenium selenium-webdriver selenium-chromedriver qa


【解决方案1】:

您对隐式等待的期望非常接近,但还有更多。

根据selenium docs wait页面:

通过隐式等待,WebDriver 轮询 DOM 一段时间 当试图找到任何元素时

所以它在等待试图找到任何元素时。这设置一次并影响每个 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,并且您的对象不存在(因为您希望元素不存在)时,您的隐式等待会导致它在抛出 NoSuchElement 并最终返回 true 之前等待 10 秒。

展望未来,您可能有几个选择。

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

警告:不要混合隐式和显式等待。这样做会导致 不可预知的等待时间。例如,将隐式等待设置为 10 秒和 15 秒的显式等待可能会导致超时 20 秒后发生。

几乎不是一个很好的选择。但是,想一想 - 如果您有一个隐式等待会等到对象 #2 准备好,您是否需要等待对象 #1 消失?

另一种选择,将您的等待包装在您自己的函数中,并在隐式等待之前将隐式等待设置为零,然后在退出时设置回 10。这很麻烦,但它可以工作。 我手头没有 IDE,但如果您需要支持让这个想法付诸实施,请告诉我。

【讨论】:

    猜你喜欢
    • 2017-04-19
    • 1970-01-01
    • 2023-04-08
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 2018-01-24
    • 2020-01-20
    相关资源
    最近更新 更多