Selenium (Java) - 继续单击按钮,直到元素中存在特定文本,如果超过一定时间量,则失败



我有一个场景,我可以通过单击启动后台进程的按钮来停止引擎,并且每次只有在单击页面中的Refresh Status按钮后,我才能看到引擎的当前状态。问题是引擎停止的时间从 30 秒到 2 分钟不等,具体取决于服务器上的负载。我真的不想用Thread.sleep()编写一个while循环,因为这是一个坏主意,并且会不必要地增加硒的测试时间。有没有一种直观的方法可以每次等待 20 秒并单击Refresh Status按钮,直到元素中出现Offline文本并且整个过程的超时时间为 3 分钟?

您可以扩展ExpectedConditions类并覆盖静态方法textToBePresentInElementLocated,如果您会看到实现非常简单:

public static ExpectedCondition<Boolean> textToBePresentInElementLocated(
      final By locator, final String text) {
    return new ExpectedCondition<Boolean>() {
      @Override
      public Boolean apply(WebDriver driver) {
        try {
          String elementText = findElement(locator, driver).getText();
          return elementText.contains(text);
        } catch (StaleElementReferenceException e) {
          return null;
        }
      }
      @Override
      public String toString() {
        return String.format("text ('%s') to be present in element found by %s",
            text, locator);
      }
    };
  }

只需将此方法中的 element.click() 添加到适当的位置,然后在 WebDriverWait 中使用您的类扩展类

我会做这样的事情。

/**
 * Attempts to stop the engine within a specified time
 * 
 * @param driver 
 *            the WebDriver instance
 * @return true if the engine has stopped, false otherwise
 * @throws InterruptedException
 */
public boolean StopEngine(WebDriver driver) throws InterruptedException
{
    driver.findElement(By.id("stopEngineButton")).click(); // click the stop engine button
    boolean found = false;
    int i = 0;
    while (!found && i < 6) // 6 * 20s = 2 mins
    {
        Thread.sleep(20000);
        driver.findElement(By.id("RefreshStatus")).click(); // click the Refresh Status button
        // not sure if you need a wait here to let the statusElement update
        found = driver.findElement(By.id("statusElement")).getText().equals("Offline"); // compare the current engine status to Offline
        i++;
    }
    return found;
}

您还可以通过将轮询间隔和超时作为参数传递来修改此代码以使其更加灵活。

最新更新