How to display html using QWebView. Python?
Asked Answered
S

1

12

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>
Saddler answered 14/11, 2012 at 18:13 Comment(0)
B
23

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_()
Bitartrate answered 14/11, 2012 at 19:42 Comment(2)
Thank you very much! Your example is just great!Saddler
Thanks, but when I run this _result_available() never gets called though __init__(self) does.Loydloydie

© 2022 - 2024 — McMap. All rights reserved.