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

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

问题描述

我正在尝试使用Java和Selenium WebDriver自动化一些测试用例.我有以下情况:

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

  • 有一个名为产品"的页面.当我点击查看详细信息"链接时 在产品"页面上,将显示一个包含项目详细信息的弹出窗口(模态对话框).
  • 当我单击弹出窗口中的关闭"按钮时,弹出窗口关闭, 页面会自动刷新(页面正在重新加载,内容保持不变).
  • 关闭弹出窗口后,我需要在 同一页.但是,当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 remain 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驱动程序实例后立即设置隐式等待:

  1. Set implicit wait immediately after creating the web driver instance:

_ = driver.Manage().Timeouts().ImplicitWait;

这将尝试等到每次页面导航或页面重新加载完全加载页面时.

This will try to wait until the page is fully loaded on every page navigation or page reload.

页面导航后,调用JavaScript return document.readyState,直到返回"complete". Web驱动程序实例可以用作JavaScript执行程序.示例代码:

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

  • 检查URL是否与您期望的模式匹配.

  • Check if the URL matches the pattern you expect.

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

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