硒 -- 如何等到页面完全加载

2022-08-31 09:40:00

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

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

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

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

如果在单击“添加项”按钮之前使用测试用例,则测试用例可以正常工作。此问题是否有任何其他解决方法?Thread.sleep(3000);


答案 1

3个答案,您可以将其组合在一起:

  1. 在创建 Web 驱动程序实例后立即设置隐式等待:

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

    这将尝试等到页面完全加载到每个页面导航或页面重新加载。

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

    C#

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

    爪哇岛

    new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
          webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
    
  3. 检查 URL 是否与您期望的模式匹配。


答案 2

似乎您需要等待页面重新加载,然后单击“添加”按钮。在这种情况下,您可以等待“添加项目”元素变得陈旧,然后再单击重新加载的元素:

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

推荐