2012-07-06 44 views
8

我試圖以編程方式測試網站列表的加載時間。目的是大致模擬用戶會感知的頁面加載時間。在硒中測試頁面加載時間的正確方法?

我的第一種方法是調用一個循環中執行以下操作:

startTime = System.currentTimeMillis(); 
    driver.get("http://" + url); 
    diff = System.currentTimeMillis() - startTime; 
    System.out.println("Load time was " + diff); 

的問題是,有時我得到的時間結果的頁面確實加載之前(即我得到50ms的時間),所以我想控制正在交給driver.get()完成之前的下一條指令。

我該怎麼做才能改進這個測試?

編輯:

由於user1258245建議我可以等因素來加載,但問題是我不知道是哪個網頁生病預先加載。

+0

見http://stackoverflow.com/questions/6112863/timing-page-load-times- in-selenium – Avery 2012-07-06 15:14:39

回答

13

有2種方法可以爲您提供有意義的數據。

  1. 與Selenium一起使用Browsermob Proxy。這是一個Python的例子,但它幾乎是在Java中

    from browsermobproxy import Server 
    server = Server("path/to/browsermob-proxy") 
    server.start() 
    proxy = server.create_proxy() 
    
    from selenium import webdriver 
    profile = webdriver.FirefoxProfile() 
    profile.set_proxy(proxy.selenium_proxy()) 
    driver = webdriver.Firefox(firefox_profile=profile) 
    
    proxy.new_har("google") 
    driver.get("http://www.google.co.uk") 
    proxy.har # returns a HAR JSON blob 
    
    proxy.stop() 
    driver.quit() 
    

是從proxy.har返回,這僅僅是一個JSON BLOB HAR檔案一樣,會給你你需要的信息。我blogged今年早些時候

  1. 另一種方法是使用現代瀏覽器中可用的導航計時規範。所有你需要做的是執行一些JavaScript,您將得到頁面加載的細節等

    ((JavascriptExecutor)driver).executeScript("var performance = window.performance || {};" + 
          "var timings = performance.timing || {};"+ 
          "return timings;"); 
    
    /* The hashmap returned will contain something like the following. 
    * The values are in milliseconds since 1/1/1970 
    * 
    * connectEnd: 1280867925716 
    * connectStart: 1280867925687 
    * domainLookupEnd: 1280867925687 
    * domainLookupStart: 1280867925687 
    * fetchStart: 1280867925685 
    * legacyNavigationStart: 1280867926028 
    * loadEventEnd: 1280867926262 
    * loadEventStart: 1280867926155 
    * navigationStart: 1280867925685 
    * redirectEnd: 0 
    * redirectStart: 0 
    * requestEnd: 1280867925716 
    * requestStart: 1280867925716 
    * responseEnd: 1280867925940 
    * responseStart: 1280867925919 
    * unloadEventEnd: 1280867925940 
    */ 
    
+0

太棒了!我會去1號(第一個:)。我想我只是解析HAR文件(只是檢查,它只是json)並自己輸出結果。非常感謝您的幫助。 – cookM 2012-07-07 04:32:16