如何使用 QWebView 显示 html.Python? [英] How to display html using QWebView. Python?

查看:94
本文介绍了如何使用 QWebView 显示 html.Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在控制台中以 HTML 格式显示网页.

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>

推荐答案

由于 QT 是一个异步库,如果您在调用 后立即尝试查看 webview 的 html 数据,您可能不会有任何结果load,因为它会立即返回,并且一旦结果可用就会触发 loadFinished 信号.您当然可以尝试像我在调用 load 后立即在 _result_available 方法中所做的那样访问 html 数据,但它会返回一个空页面(这是默认行为).

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

这篇关于如何使用 QWebView 显示 html.Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆