2017-09-05 39 views
0

我嘗試使用Twisted Agent來實現HTTP客戶端並下載完整網頁的特定URL,最後測量該特定網站的加載時間頁。不幸的是,我所提供的代碼並沒有遵循HTML標籤中的內部URL,因此,從瀏覽器上的其他網站下載一些內容後需要10秒完成加載的網頁將不到一秒鐘完全加載在我的代碼中,這表明我的代碼不正確!即使我使用BrowserLikeRedirectAgent和RedirectAgent,結果也是一樣的。任何意見表示讚賞。扭曲的HTTP客戶端下載整個頁面並測量下載時間

def init_http(url): 
    userAgent = 'Twisted/%s (httpclient.py)' % (version.short(),) 
    agent = BrowserLikeRedirectAgent(Agent(reactor)) 

    def response_time_calculator(test,t1): 
     end_time = time.time() 
     response_time = end_time - t1 
     print ("Got the Whole page in: ", response_time) 

    start_time = time.time() 

    d = agent.request(
     b'GET', str(url), Headers({'user-agent': [userAgent]})) 
    def cbResponse(response): 
     if response.length is not UNKNOWN_LENGTH: 
      print('The response body will consist of', response.length, 'bytes.') 
     else: 
      print('The response body length is unknown.') 
     d = readBody(response) 
     d.addCallback(response_time_calculator, start_time) 
     return d 
    d.addCallback(cbResponse) 

回答

1

time.clock只測量Windows上的wallclock時間(奇怪)。使用time.time可測量所有平臺上的掛鐘時間。

另外,您必須實現您關注鏈接的部分。 Agent.request準確下載您請求的資源。如果該資源是一些帶有其他資源鏈接的HTML,則必須解析數據,提取鏈接並遵循它們。

你可能想看看scrapy。如果沒有,您可以添加一個稍小(不太有用)的依賴項,如html5lib。喜歡的東西:

d = readBody(response) 
    d.addCallback(load_images) 
    d.addCallback(response_time_calculator, start_time) 

... 

from twisted.internet.defer import gatherResults 
import html5lib 

def load_images(html_bytes): 
    image_requests = [] 
    doc = html5lib.parse(html_bytes) 
    for img in doc.xpath("//img"): 
     d = agent.request(img.src) 
     d.addCallback(readBody) 
     image_requests.append(d) 
    return gatherResults(image_requests) 

我省略了正確的URL分辨率(即,處理在IMG SRC相關鏈接),並沒有實際測試過這一點。它可能有許多錯誤,但希望清楚這個想法。

+0

感謝time.clock,我只需要加載標籤,所以他們的地址不能反饋給Twisted代理,有關它的任何解決方法?我寧願不在我的代碼中實現一個新的庫,所以使用scrapy並不是我想要的,我尋找一種解決方案來單獨處理Twisted和Python。 – DeFoG

+1

如果你不想使用scrapy,你需要做一些事情來解析html,找到img標籤,解釋它們的來源,併發出新的'Agent.request'調用。 Twisted中沒有任何內容會爲你做這個鏈接。 Twisted中也沒有真正的html解析器。在stdlib中有一個很老的,不太好的,但我真的推薦你使用'html5lib',它實現了html5規範,並且這是目前解析html的唯一理智方式。 –