1

我正在编写一个脚本(无头浏览器)来加载网站并记录需要加载网站资源的时间。

#!/usr/bin/env python

import gtk
import time
import webkit
import gobject


class Resource():

    __signals = [
        'content-length-received',
        'load-failed',
        'load-finished',
        'response-received'
        ]

    _start = time.time()
    _durations = {}

    def __init__(self, webkit_resource):
        self._webkit_resource = webkit_resource
        # literally copy the uri
        self._uri = "".join([c for c in self._webkit_resource.get_uri()])
        self._connect_callbacks()

    @property
    def uri(self):
        return self._uri

    def _connect_callbacks(self):
        for s_id in self.__signals:
            self._webkit_resource.connect(s_id, self._on_callback, s_id)

    def _on_callback(self, *args):
        self._durations[args[-1]] = time.time() - self._start
        print "==>", self._uri, "==>", args[-1], "==>", self._durations[args[-1]]


class Browser(webkit.WebView):

    def __init__(self):
        webkit.WebView.__init__(self)
        gobject.threads_init()
        self.connect('resource-request-starting',
                        self._on_resource_request_starting)

    def _on_resource_request_starting(self, view, frame, resource, request, response):
        c_resource = Resource(resource)


if __name__ == "__main__":
    browser = Browser()
    browser.open("http://amazon.com/")
    gtk.main()

代码运行良好,但突然间我得到以下奇怪的 Tracebacks。

==> http://amazon.com/ ==> content-length-received ==> 0.98512005806
==> http://www.amazon.com/ ==> content-length-received ==> 0.985180854797
==> http://z-ecx.images-amazon.com/images/G/01/browser-scripts/us-site-wide-css-beacon/site-wide-5659237078._V1_.css ==> content-length-received ==> 0.986252069473
==> http://z-ecx.images-amazon.com/images/G/01/browser-scripts/us-site-wide-css-beacon/site-wide-5659237078._V1_.css ==> content-length-received ==> 0.987208843231
==> http://z-ecx.images-amazon.com/images/G/01/browser-scripts/us-site-wide-css-beacon/site-wide-5659237078._V1_.css ==> load-finished ==> 0.999194860458
==>
Traceback (most recent call last):
  File "test.py", line 37, in _on_callback
    print "==>", self._uri, "==>", args[-1], "==>", self._durations[args[-1]]
AttributeError: Resource instance has no attribute '_uri'
==>
Traceback (most recent call last):
  File "test.py", line 37, in _on_callback
    print "==>", self._uri, "==>", args[-1], "==>", self._durations[args[-1]]
AttributeError: Resource instance has no attribute '_uri'
==>

我确实设置了self._uri。我实际上一个一个地复制每个字符。它是否在某处被删除?

4

0 回答 0