由于 Ajax,加载部分页面时无法在页面中等待

Unable to wait in page when partial page is getting loaded due to Ajax

我在 html 的部分标签中有一些控件,这些控件会在 ajax 请求完成时加载。现在有一种情况,其中 ajax 已加载但控件未出现在页面上,我想停止代码执行,直到所有控件都已加载并在页面上可见。

如何识别页面上是否加载了所有控件。

我不想使用以下解决方案:

1) 代码中的显式等待(因为我不知道控件何时加载)。

2) 我不想使用 wait.Until(ExpectedConditions.ElementIsVisible(By.Id(id)));(因为如果页面上不存在特定控件,它将无限期地等待)

如有任何帮助,我们将不胜感激。

  1. 创建一个 class 名为 ExtensionMethods
  2. 在此class

    中添加以下方法

    public static void WaitForPageToLoad(此 IWebDriver 驱动程序) { TimeSpan 超时 = new TimeSpan(0, 0, 30); WebDriverWait wait = new WebDriverWait(driver, timeout);

    IJavaScriptExecutor javascript = driver as IJavaScriptExecutor;
    if (javascript == null)
        throw new ArgumentException("driver", "Driver must support javascript execution");
    
    wait.Until((d) =>
    {
        try
        {
            string readyState = javascript.ExecuteScript(
            "if (document.readyState) return document.readyState;").ToString();
            return readyState.ToLower() == "complete";
        }
        catch (InvalidOperationException e)
        {
            //Window is no longer available
            return e.Message.ToLower().Contains("unable to get browser");
        }
        catch (WebDriverException e)
        {
            //Browser is no longer available
            return e.Message.ToLower().Contains("unable to connect");
        }
        catch (Exception)
        {
            return false;
        }
    });
    

    }

此代码将等待所有 JavaScript 加载完毕。

  1. 在与页面上的元素交互之前使用此方法