How to display html using QWebView. Python?

Vor picture Vor · Nov 14, 2012 · Viewed 31k times · Source

How to display webpage in HTML format in console.

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

app = QApplication(sys.argv)
view = QWebView()
view.load(QUrl('http://example.com')
# What's next? how to do something like:
# print view.read() ???
# to display something similar to that:
# <html><head></head><body></body></html>

Answer

andrean picture andrean · Nov 14, 2012

As QT is an async library, you probably won't have any result if you immediately try to look at the html data of your webview after calling load, because it returns immediately, and will trigger the loadFinished signal once the result is available. You can of course try to access the html data the same way as I did in the _result_available method immediately after calling load, but it will return an empty page (that's the default behavior).

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


class Browser(QWebView):

    def __init__(self):
        QWebView.__init__(self)
        self.loadFinished.connect(self._result_available)

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

if __name__ == '__main__':
    app = QApplication(sys.argv)
    view = Browser()
    view.load(QUrl('http://www.google.com'))
    app.exec_()