python - 在QWebEngineView浏览器中保存html文件

标签 python pyqt pyqt5 python-3.6 qwebengineview

我正在尝试使用 Python QWebEngineView 创建自己的浏览器。我遵循了适用于 PyQt5 之前版本(2015 年左右)的教程,但由于最近的更新,之前代码的某些部分不再起作用。

我已经修复了大部分错误,但无法执行 html 文件打开/保存。当我单击“保存”按钮时,我总是收到系统错误。以下是我的文件保存代码:

(QMainWindow类)

save_file_action = QAction(QIcon("disk--pencil.png"), "Save Page As...", self)
save_file_action.setStatusTip("Save current page to file")
file_menu.addAction(save_file_action)

(保存文件函数)

def save_file(self):
    filename, _ = QFileDialog.getSaveFilename(self, "Save Page As", "",
        "Hypertext Markup Language (*.htm *.html);;"    
        "All files(*.*)")

    if filename:
        html = self.browser.page().mainFrame().toHtml()
        with open(filename, 'w') as f:
            f.write(html)

谢谢。

最佳答案

QtWebEnginetoHtml() 函数是异步的,因此它不会直接返回任何内容,但您必须向其传递一个回调,以便在该函数中返回html 中,为了将该进程异步转换为同步,我们在信号的帮助下使用 QEventLoop :

import sys

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *

class Browser(QMainWindow):
    htmlFinished = pyqtSignal()
    def __init__(self, *args, **kwargs):
        QMainWindow.__init__(self, *args, **kwargs)
        self.mHtml = ""
        self.view = QWebEngineView()
        self.setCentralWidget(self.view)
        self.view.setUrl(QUrl("http://www.google.com/"))
        file_menu = QMenu(self.menuBar())
        file_menu.setTitle("File")
        save_file_action = QAction(QIcon("disk--pencil.png"), "Save Page As...",self)
        file_menu.addAction(save_file_action)
        self.menuBar().addAction(file_menu.menuAction())
        save_file_action.triggered.connect(self.save_file)

    def callback(self, html):
        self.mHtml = html
        self.htmlFinished.emit()

    def save_file(self):
        filename, _ = QFileDialog.getSaveFileName(self, "Save Page As", "", "Hypertext Markup Language (*.htm *.html);;" "All files(*.*)")
        if filename:
            self.view.page().toHtml(self.callback)
            loop = QEventLoop()
            self.htmlFinished.connect(loop.quit)
            loop.exec_()
            with open(filename, 'w') as f:
                f.write(self.mHtml)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Browser()
    w.show()
    sys.exit(app.exec_())

关于python - 在QWebEngineView浏览器中保存html文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48386253/

相关文章:

python - 验证前馈网络的有效性

python - 在 QPlainTextEdit() 中禁用回车(按 Enter 键)

python - time.sleep() 和 BackGround Windows PyQt5

python - PyQt5 keyPressEvent 不适用于终止 App Qt Designer

python - 如何验证您在 Azure 上是否有足够的资源

python - 在 Pandas 中,如何根据多个列的组合创建唯一 ID?

python - PyQt4 库和在 Mac OS 上的安装

python - 更改环境变量中的 QT_PLUGIN_PATH 会导致程序失败

python - 使用 pip download -rrequirements.txt 的问题

python - 使用 QStandardItemModel 更改 QTableView 的行颜色