Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display html using QWebView. Python?

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>
like image 989
Vor Avatar asked Nov 14 '12 18:11

Vor


1 Answers

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_()
like image 57
andrean Avatar answered Oct 05 '22 20:10

andrean