在PyQt4中的loadFinished信号之后打印网站的HTML。蟒蛇

时间:2012-11-15 18:51:07

标签: python webkit pyqt4

我刚开始学习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_()

1 个答案:

答案 0 :(得分:2)

您需要调用print_html方法,例如

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

()

末尾注意print_html

然后它仍然无法工作,因为你的print_html无法访问视图,你可以将视图传递给它,但它不是一种正确的方法来进行面向对象的编程。你应该从QWebView推导浏览器并绑定到__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_()