0

我刚开始学习 PyQt4,并玩信号和插槽,请帮助我修复我的代码,以便在站点完全下载后,它将打印此网页的 html。现在它只是在“加载完成”后停止

我的代码:

#! /usr/bin/env python2.7

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
import sys

class Browser(QObject):
    def __init__(self):
        QObject.__init__(self)
    def print_percent(self, percent):
        print percent
    def print_load_finished(self):
        print 'Load Finished'
        self.print_html
    def print_html(self, ok):
        frame = QWebView.page().mainFrame()
        print unicode(frame.toHtml()).encode('utf-8')

if __name__=='__main__':
    app = QApplication(sys.argv)
    view = QWebView()
    br = Browser()
    url = QUrl('http://python.org')
    view.loadFinished.connect(br.print_load_finished)
    view.loadProgress.connect(br.print_percent)
    view.load(url)
    view.show()
    app.exec_()
4

1 回答 1

2

您需要调用print_html方法,例如

 def print_load_finished(self):
        print 'Load Finished'
        self.print_html()

注意()在末尾print_html

但是它仍然无法工作,因为您print_html无法访问视图,您可以将视图传递给它,但这不是进行面向对象编程的正确方法。您应该从 may be 派生 BrowserQWebView并绑定到中的事件__init__,所以它应该是这样的

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
import sys

class Browser(QWebView):
    def __init__(self):
        super(Browser, self).__init__()
        self.loadFinished.connect(self.print_load_finished)
        self.loadProgress.connect(self.print_percent)

    def print_percent(self, percent):
        print percent

    def print_load_finished(self):
        print 'Load Finished'
        self.print_html()

    def print_html(self):
        frame = self.page().mainFrame()
        print unicode(frame.toHtml()).encode('utf-8')

if __name__=='__main__':
    app = QApplication(sys.argv)
    br = Browser()
    url = QUrl('http://python.org')
    br.load(url)
    br.show()
    app.exec_()
于 2012-11-15T19:11:04.867 回答