2011-02-02 77 views
2

我試圖創建一個小型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 

回答

2

我已經設法解決這個問題:創建QWebPage在GUI線程(QApplication事件循環的線程)中修復了這個問題。

它似乎是第二次使用QWebPage,它試圖訪問瀏覽器緩存(即使它已被配置禁用)。但是如果第一個QWebPage不是在主GUI線程中創建的,則緩存有些配置不正確,無法使用。

要在主GUI線程中創建QWebPage我正在使用觸發QWebPage初始化和結果獲取的自定義QEvent(類型爲User的QEvent)。

+0

你可以發佈解決方案嗎? – hoju 2012-02-07 05:49:01

相關問題