selenium with PhantomJs wait till page fully loade

2019-04-07 14:08发布

问题:

I use Selenium with Phantomjs, and want to get the page content after the page fully loaded.

I tried http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp but it seems not working with phantomjs

Explicit wait:

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

Another test:

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;
}

Or implicit wait:

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

    content = driver.PageSource;

    driver.Quit();
}

The content is still lacking. The only way is to put Thread.Sleep(waitTime); which is not a good solution for this.

Thanks.

回答1:

For your "Explicit wait:" option, I think the correct sequence should be:

1) Navigate to target url by:

driver.Navigate().GoToUrl(url);

2) Wait until the target url fully loaded by

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

In this way next line will wait page fully loaded before read PageSource.



回答2:

I have created a extension method. In this method you can put your condition.

  public static bool WaitUntil(this IWebDriver driver, Func<IWebDriver, bool> expression, int timeOutSeconds = 10)
    {

        TimeSpan timeSpent = new TimeSpan();

        bool result = false;
        while (timeSpent.TotalSeconds < timeOutSeconds)
        {

            result = expression.Invoke(driver);

            if (result == true)
            {
                break;
            }
            Thread.Sleep(timeSleepingSpan);
            timeSpent = timeSpent.Add(new TimeSpan(0, 0, 0, 0, timeWaitingSpan));

        }
        return result;

    }

Like

       driver.WaitUntil(d => d.Url.Equals("https://www.meusite.com/"));


回答3:

Try something like this:

try (
  ExpectedConditions.presenceOfElementLocatedBy
  ExpectedConditions.visibilityOfElementLocatedBy
) catch error if both conditions are not met