我試圖創建一個小型Web服務器,它使用Webkit加載一個URL以從網頁中提取一些數據(例如:標題,圖像大小...) 。無法在同一個應用程序中使用QWebPage兩次
我正在使用PyQt4從python訪問webkit。對於每個請求,我創建一個QThread: - 創建QWebPage對象, - 運行事件循環 - 當網頁加載完成(loadFinished信號)時,某些代碼從QWebPage的mainFrame中提取數據並殺死QThread
這首次運行良好,網頁被加載,包括其所有資源(CSS,圖像)。 第二次我要求服務器加載一個url,網頁被加載,但沒有它的資源(沒有CSS,沒有圖像)。所以當我嘗試檢索圖像大小時,所有大小都設置爲0,0。
下面是一些代碼snipset:
# The QThread responsible of loading the WebPage class WebKitThread(QThread): def __init__(self, url): QThread.__init__(self) self.url = url self.start() def run(self): self.webkitParser = WebKitParser(self.url) self.exec_() class WebKitParser(QWebPage): def __init__(self, url, parent=None): QWebPage.__init__(self, parent) self.loadFinished.connect(self._loadFinished) self.mainFrame().load(QUrl(url)) def _loadFinished(self, result): self.computePageProperties() QThread.currentThread().exit() def computePageProperties(self): # Some custom code that reads title, image size... self.computedTitle=XXXXXXXX
調用代碼(即對HTTP請求的響應)正在執行:
t = WebKitThread(url) t.wait() # do some stuff with properties of WebKitParser print t.webkitParser.computedTitle
你可以發佈解決方案嗎? – hoju 2012-02-07 05:49:01