我们怎样才能获得使用Selenium WebDriver加载页面的准确时间?

Jas*_*vra 8 java selenium webdriver selenium-webdriver

我们怎样才能获得使用Selenium WebDriver加载页面的准确时间?

我们使用Thread.sleep

我们使用implicitlyWait

我们使用WebDriverWait

但是如何使用Selenium WebDriver获取加载页面的确切时间?

Har*_*ddy 16

如果您想知道使用Selenium WebDriver(又名Selenium 2)完全加载页面需要多长时间.

通常,只有在页面完全加载后,WebDriver才会将控制权返回给您的代码.

因此,以下Selenium Java代码可以帮助您找到页面加载的时间 -

long start = System.currentTimeMillis();

driver.get("Some url");

long finish = System.currentTimeMillis();
long totalTime = finish - start; 
System.out.println("Total Time for page load - "+totalTime); 
Run Code Online (Sandbox Code Playgroud)

如果这不起作用,那么你将不得不等到页面上显示一些元素 -

 long start = System.currentTimeMillis();

driver.get("Some url");

WebElement ele = driver.findElement(By.id("ID of some element on the page which will load"));
long finish = System.currentTimeMillis();
long totalTime = finish - start; 
System.out.println("Total Time for page load - "+totalTime); 
Run Code Online (Sandbox Code Playgroud)


Rip*_*sim 5

您可以使用org.apache.commons.lang3.time包的StopWatch对象。以下是使用Java的Selenium WebDriver的完整代码:

import org.apache.commons.lang3.time.StopWatch;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class TimerInSeleniumWebDriver {
    public static void main(String[] args) {
        WebDriver driver;
        driver = new FirefoxDriver();       
        StopWatch pageLoad = new StopWatch();
        pageLoad.start();
        //Open your web app (In my case, I opened facebook)
        driver.get("https://www.facebook.com/");
        // Wait for the required any element (I am waiting for Login button in fb)
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.id("u_0_l")));

        pageLoad.stop();
        //Get the time
        long pageLoadTime_ms = pageLoad.getTime();
        long pageLoadTime_Seconds = pageLoadTime_ms / 1000;
        System.out.println("Total Page Load Time: " + pageLoadTime_ms + " milliseconds");
        System.out.println("Total Page Load Time: " + pageLoadTime_Seconds + " seconds");
        driver.close();
    }
}
Run Code Online (Sandbox Code Playgroud)