Selenium - 如何等待页面完全加载

sta*_*low 62 java selenium-webdriver

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

  • 有一个名为"产品"的页面.当我点击"产品"页面中的"查看详细信息"链接时,会出现一个包含该项目详细信息的弹出窗口(模式对话框).
  • 当我点击弹出窗口中的"关闭"按钮时,弹出窗口关闭,页面自动刷新(页面刚刚重新加载,内容保持不变).
  • 关闭弹出窗口后,我需要点击同一页面中的"添加项目"按钮.但是当WebDriver试图找到"添加项目"按钮时,如果互联网速度太快,WebDriver可以找到并单击该元素.

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

  • 即使使用了不同的等待,所有等待条件也变为真(因为重新加载之前和之后页面中的内容相同),甚至在页面重新加载和StaleElementReferenceException 发生之前.

如果Thread.sleep(3000);在单击"添加项目"按钮之前使用测试用例,则工作正常.这个问题还有其他解决方法吗?

Kim*_*ann 76

3个答案,你可以结合:

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

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

C#

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

Java的

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

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

  • 我相信 python 是(随意将其添加到您的答案中): selenium.webdriver.support.ui.WebDriverWait(self.driver, 10).until(lambda d: d.execute_script("return document.readyState") = = "完成") (4认同)
  • 能否请您给出示例代码以在Java中实现第2点 (2认同)
  • driver.manage().timeouts().在java中的implicitlyWait()要求2个参数(长arg0,TimeUnit arg1)这是超时还是什么? (2认同)

Flo*_* B. 14

在点击"添加"按钮之前,您似乎需要等待重新加载页面.在这种情况下,您可以在单击重新加载的元素之前等待"Add Item"元素变为陈旧:

WebDriverWait wait = new WebDriverWait(driver, 20);
By addItem = By.xpath("//input[.='Add Item']");

// get the "Add Item" element
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(addItem));

//trigger the reaload of the page
driver.findElement(By.id("...")).click();

// wait the element "Add Item" to become stale
wait.until(ExpectedConditions.stalenessOf(element));

// click on "Add Item" once the page is reloaded
wait.until(ExpectedConditions.presenceOfElementLocated(addItem)).click();
Run Code Online (Sandbox Code Playgroud)

  • 万一您需要等待多个操作发生的完美示例。 (2认同)

noo*_*oor 9

在单击添加项目之前,您可以通过多种方式执行此操作:

WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.elementToBeClickable(By.id("urelementid")));// instead of id u can use cssSelector or xpath of ur element.


or

wait.until(ExpectedConditions.visibilityOfElementLocated("urelement"));
Run Code Online (Sandbox Code Playgroud)

你也可以这样等 如果您想等到上一页元素不可见:

wait.until(ExpectedConditions.invisibilityOfElementLocated("urelement"));
Run Code Online (Sandbox Code Playgroud)

这里是你找到所有可用于等待及其文档的selenium webdriver api的链接.

https://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html