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.
We can wait until the page is completely loaded in Selenium webdriver by using the JavaScript Executor. Selenium can run JavaScript commands with the help of the executeScript method. We have to pass return document.
We can get Selenium to recognize that a page is loaded. We can set the implicit wait for this purpose. It shall make the driver to wait for a specific amount of time for an element to be available after page loaded.
Implicit Wait directs the Selenium WebDriver to wait for a certain measure of time before throwing an exception. Once this time is set, WebDriver will wait for the element before the exception occurs. Once the command is in place, Implicit Wait stays in place for the entire duration for which the browser is open.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With