Selenium - 如何等待页面完全加载 [英] Selenium - How to wait until page is completely loaded

查看:2664
本文介绍了Selenium - 如何等待页面完全加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java和Selenium Web驱动程序自动化一些测试用例。我有以下情况:

I am trying to automate some test cases using Java and Selenium web driver. I have the following scenario:


  • 有一个名为'Products'的页面。当我点击'产品'页面中的'查看详情'链接
    时,会出现一个包含该项目详情的弹出窗口(模态对话框)。

  • 当我点击时弹出窗口关闭弹出窗口中的'关闭'按钮,页面自动刷新
    (页面正在重新加载,
    内容保持不变)。

  • 关闭弹出窗口后,我需要点击
    同一页面中的添加项目按钮。但是当webdriver试图找到添加项目按钮时,如果网速太快,则
    ,webdriver可以找到并点击
    元素。

  • There is a page named 'Products'. When I click on 'View Details' link in the 'Product' page, a popup (modal-dialog) containing the details of the item appears.
  • When I click on the 'Close' button in the popup the popup closes and the page automatically refreshes (the page is just reloading, the contents remains unchanged).
  • After closing the popup I need to click on 'Add Item' button in the same page. But when webdriver trying to find the 'Add Item' button, if the internet speed is too fast, webdriver can find and click the element.

但是如果互联网很慢,webdriver会在
页面刷新之前找到该按钮,但只要webdriver单击该按钮,就会刷新
页面并发生StaleElementReferenceException。

But if the internet is slow, webdriver finds the button before the page refresh, but as soon as the webdriver click on the button, the page refreshes and StaleElementReferenceException occurs.

如果 Thread.sleep(在点击添加项目按钮之前使用3000); 。这个问题还有其他解决办法吗?

The test case works fine if Thread.sleep(3000); is used before clicking on the 'Add Item' button. Is there any other workaround for this problem?

推荐答案

3个答案,你可以把它们结合起来:

3 answers, which you can combine:

1。)创建Web驱动程序实例后立即设置隐式等待: driver.manage()。timeouts()。implicitlyWait()。这将尝试等到页面在每个页面导航或页面重新加载时完全加载。

1.) Set implicit wait immediately after creating the web driver instance: driver.manage().timeouts().implicitlyWait(). This will try to wait until the page is fully loaded on every page navigation or page reload.

2。)页面导航后,调用JavaScript 返回document.readyState 直到完成被返回。 Web驱动程序实例可以充当JavaScript执行程序。示例代码:

2.) After page navigation, call JavaScript return document.readyState until "complete" is returned. The web driver instance can serve as JavaScript executor. sample code:

C#

new WebDriverWait(driver, MyDefaultTimeout).Until(
    d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));

Java

new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
          webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));

3。)在2.)之后,检查URL是否与您期望的模式匹配。

3.) After 2.), check if the URL matches the pattern you expect.

这篇关于Selenium - 如何等待页面完全加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆