How to get exact page load time for all web pages using Selenium WebDriver with Java?

Hmm, it sounds tricky, finding how much time does it take for a page to load that we navigate to from our automation script. But, its possible using Selenium WebDriver with Java.

Following code snippet may help us getting the page load time.

Step 1 : Create WebDriverEventListenerClass.java file, which extends AbstractWebDriverEventListener class, overrides two event methods as shown in code snippet.

public class WebDriverEventListenerClass extends AbstractWebDriverEventListener {

             long startTime, endTime;

            @Override
             public void beforeNavigateTo(String arg0, WebDriver arg1) {
                          startTime = System.currentTimeMillis();
             }

             @Override
             public void afterNavigateTo(String arg0, WebDriver arg1) {

                         endTime = System.currentTimeMillis();
                        System.out.println(“Page load time for ” + arg0 + ” is (in milliseconds) : ” + (endTime – startTime));
       

              }

}

To know more about Listener events visit What is Listeners in Selenium WebDriver?

Step 2 : Create GetPageLoadTime.java file, contains a simple automation script which opens a google.com.

public class GetPageLoadTime {

             public static void main(String[] args) {

                          WebDriver ffDriver = new FirefoxDriver();

                          EventFiringWebDriver driver = new EventFiringWebDriver(ffDriver);
                          WebDriverEventListenerClass eventListener = new WebDriverEventListenerClass();

                          driver.register(eventListener);
                          driver.get(“http://www.google.com”);
                          driver.quit();

              }
}

Output : On console, the page load time for google.com will be displayed in milliseconds.

Visit What is Listeners in Selenium WebDriver? for more information about Event listeners in Selenium WebDriver.

Hope you liked it!

Cheers 🙂

Advertisements

#abstractwebdrivereventlistener, #get-page-load-time-in-selenium-webdriver, #listeners-in-webdriver, #webdriver