Why is QWebView.loadFinished called several times

2019-02-07 08:58发布

As per the documentation, loadFinished should be emitted only after all the page elements have finished loading. This should mean that it'll be called only once, however I've noticed that on some sites like youtube.com, it gets called twice ? Is there any other way to get around this bug or whats the most reliable way to detect page.load event ?

Here's the test code :

import sys
from PyQt4 import QtCore, QtGui, QtWebKit
from PyQt4.QtCore import QUrl
from PyQt4.QtGui import QApplication

def onDone(val):
    print "Done ...",val

def onStart():
    print "Started..."   

app = QApplication(sys.argv)
ui =  QtWebKit.QWebView()
ui.loadStarted.connect(onStart)
ui.loadFinished.connect(onDone)

ui.load(QUrl("http://www.youtube.com"))   
ui.showMaximized()
sys.exit(app.exec_())

The output:

Started...
Done ... True
Started...
Done ... True

Edit: There's an almost same question but its > 2yrs old and still unanswered.

2条回答
祖国的老花朵
2楼-- · 2019-02-07 09:13

The load* signals are fired once for each frame that is loaded.

To capture only the first set of signals, connect to the corresponding signals of the main frame:

ui.page().mainFrame().loadStarted.connect(onStart)
ui.page().mainFrame().loadFinished.connect(onDone)

You can verify that other frames are being loaded by connecting to the frameCreated signal, which will fire once for each subsequent frame created after the main frame has loaded:

def onFrame(val):
    print 'Frame Created:', val.frameName()

ui.page().frameCreated.connect(onFrame)
查看更多
欢心
3楼-- · 2019-02-07 09:15

I am quite sure that happens when you modify the DOM like if it was a string. I am sure QWebKit runs JS code, so it could modify the DOM after it was onDone().

You should probably create an onDoneFirst method that only fires once.

查看更多
登录 后发表回答