【问题标题】:robotframework+Selenium: How to wait until page reloadedrobotsframework + Selenium:如何等到页面重新加载
【发布时间】:2020-12-31 16:02:39
【问题描述】:

当我单击按钮时,它会触发重新加载当前页面(假设所有显示的内容都相同)。 如何等待重新加载过程?

在下面的代码失败的情况下,

    Click Element    btn1    # btn1 triggers the current page to be reloaded
    Wait Until Element Is Visible    btn2    timeout=10s    # This line succeeds because the page is yet reloaded and btn2(not refreshed, old one) is visble
    Click Element      btn2    # This line fails because the page is not yet stable 

如何实现如下代码?

    Click Element    btn1
    **Wait Until The Current Page Is Reloaded And Became Stable Again**
    Click Element      btn2

【问题讨论】:

  • 尝试先等待 btn2 不可见。所以旧的应该先消失,然后等待它再次出现。

标签: selenium robotframework


【解决方案1】:

对我来说效果很好的一种技术是在 python 中编写一个关键字来执行以下操作:

  • 获取对<html> 元素的引用,
  • 执行导致页面刷新的操作,
  • 使用 selenium 方法,让您等待元素过时(以便您知道刷新已经开始)
  • 等待 javascript 变量 document.readState “完成”(以便您知道刷新已完成)
  • 可选择等待您的特定应用程序可能需要的任何其他内容(以便您知道您的应用程序已准备就绪)

如果将其实现为上下文管理器,则可以将触发刷新的代码放在with 语句的主体内。

这是我在my page object library中使用的实现

class PageObject(six.with_metaclass(ABCMeta, object)):
    ...
    @property
    def selib(self):
        return self.builtin.get_library_instance("SeleniumLibrary")

    @property
    def browser(self):
        return self.selib._current_browser()

    @contextmanager
    def _wait_for_page_refresh(self, timeout=10):
        """Context manager that waits for a page transition.

        This keyword works by waiting for two things to happen:

        1) the <html> tag to go stale and get replaced, and
        2) the javascript document.readyState variable to be set
           to "complete"
        """
        old_page = self.browser.find_element_by_tag_name('html')
        yield
        WebDriverWait(self.browser, timeout).until(
            staleness_of(old_page),
            message="Old page did not go stale within %ss" % timeout
        )
        self.selib.wait_for_condition("return (document.readyState == 'complete')", timeout=10)

然后您可以在自己的库关键字中使用它,如下所示:

class LoginPage(PageObject):
    ...
    def click_the_submit_button(self):
        """Click the submit button, and wait for the page to reload"""
        with self._wait_for_page_refresh():
            self.selib.click_button(self.locator.submit_button)

【讨论】:

    【解决方案2】:

    抛开关于稳定页面意味着什么的讨论,这可能会奏效。这是评论部分的建议:

    Click Element    btn1
    Wait Until Element Is Not Visible    btn2    timeout=10
    Wait Until Element Is Visible    btn2    timeout=10
    Click Element      btn2
    

    【讨论】:

      猜你喜欢
      • 2016-08-04
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多