使用PhantomJs的selenium要等到页面完全加载吗?[英] selenium with PhantomJs wait till page fully loaded?

问题描述

我将 Selenium 与 Phantomjs 一起使用,并希望在页面完全加载后获取页面内容.

我试过 http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp 但它似乎不适用于 phantomjs

显式等待:

using (IWebDriver driver = new PhantomJSDriver())
{
    IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));
    wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));

    driver.Navigate().GoToUrl(url);

    content = driver.PageSource;

    driver.Quit();
}

另一个测试:

using (IWebDriver driver = new PhantomJSDriver())
{
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

    driver.Url = url;

    IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
        {
            return d.FindElement(By.Id("footer")); // failed because it's not yet loaded full content 
        });

    content = driver.PageSource;
}

或隐式等待:

using (IWebDriver driver = new PhantomJSDriver())
{
    driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30));
    driver.Navigate().GoToUrl(url);

    content = driver.PageSource;

    driver.Quit();
}

内容仍然缺乏.唯一的方法是把 Thread.Sleep(waitTime);这不是一个好的解决方案.

谢谢.

推荐答案

对于您的"显式等待:"选项,我认为正确的顺序应该是:

1) 通过以下方式导航到目标网址:

driver.Navigate().GoToUrl(url);

2) 等到目标url被完全加载

IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));
wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));

这样下一行将在读取 PageSource 之前等待页面完全加载.

本文地址:https://www.itbaoku.cn/post/1739966.html