How to display html using QWebView. Python?

♀尐吖头ヾ 提交于 2019-12-03 09:27:11

问题


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>

回答1:


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_()


来源:https://stackoverflow.com/questions/13384749/how-to-display-html-using-qwebview-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!