
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Wait for Page to Load in Selenium WebDriver
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.readyState as a parameter to the executeScript method and then verify if the value returned by this command is complete.
Syntax
JavascriptExecutor j = (JavascriptExecutor)driver; if (j.executeScript("return document.readyState").toString().equals("complete")){ System.out.println("Page has loaded"); }
Example
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class PageLdWait{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/index.htm"); // JavaScript Executor to check ready state JavascriptExecutor j = (JavascriptExecutor)driver; if (j.executeScript("return document.readyState").toString().equals("complete")){ System.out.println("Page has loaded"); } //iterate 50 times after every one second to verify if in ready state for (int i=0; i<50; i++){ try { Thread.sleep(1000); }catch (InterruptedException ex) { System.out.println("Page has not loaded yet "); } //again check page state if (j.executeScript("return document.readyState").toString().equals("complete")){ break; } } } }
Output
Advertisements