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

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

问题描述

我正在尝试使用 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.

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

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